2017-07-31 185 views
-2

我在Hackerrank上做了这个挑战,我尝试了所有可以做的事情,但没有做对。 挑战细节为:https://www.hackerrank.com/challenges/dynamic-array/problem指针指向二维数组的指针的迭代

我的代码是:

#include <cmath> 
#include <cstdio> 
#include <vector> 
#include <iostream> 
#include <algorithm> 
using namespace std; 


int main() { 
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 
    int noOfSequence, noOfQuery; 
    int lastAnswer = 0, j=0; 
    int query, x, y; 

    cin>>noOfSequence>>noOfQuery; 

    int *seqLength = new int[noOfSequence]; 
    for(int i=0; i<noOfSequence; i++){ 
     seqLength[i] = 0; 
    } 

    int **seqList = new int*[noOfSequence]; 
    for(int i=0; i<noOfSequence; i++){ 
     seqList[i] = new int [noOfSequence]; 
    } 

    for(int i=0; i<noOfQuery; i++){ 
     cin>>query>>x>>y; 
     switch(query){ 
      case 1: { 
         int seqListIndex = (x^lastAnswer) % noOfSequence; 
         *(seqList[seqListIndex] ++) = y; 
         seqLength[seqListIndex] += 1; 
         break; 
        } 
      case 2: { 
         int seqListIndex = (x^lastAnswer) % noOfSequence; 
         lastAnswer = seqList[seqListIndex][y%seqLength[seqListIndex]]; 
         cout<<lastAnswer; 
         break; 
        } 
      default: cout<<"default"<<endl; 
     } 
    } 

    return 0; 
} 

1. int **seqList是指向指针数组。指针数组进一步指向个别数组int

2. int *seqLength是指向整数数组的指针。这个整数数组跟踪上面提到的数组长度。 3. int seqListIndex表示指针数组的索引。

我猜这个lastAnswer的计算方式有问题。我已经尽可能检查了它,但仍然找不到任何东西。 我也尝试了解我们如何迭代int数组,但多一点知识会很棒。

+0

*但是没有得到它的权利*。你是什​​么意思? –

+0

为什么你不使用矢量?你知道'^'是按位[独家或](https://en.wikipedia.org/wiki/Exclusive_or)运算符吗? –

+0

呃....自动生成器包含了'',对于你应该用什么来解决C++中的这个问题并不那么微妙。 – WhozCraig

回答

0

问题是,您将seqList[seqListIndex]当作指向“下一个元素”的指针,但y%seqLength[seqListIndex]是与其原始值的偏移量。

“下一个元素” 的指数是seqLength[seqListIndex],所以更换

*(seqList[seqListIndex] ++) = y; 

seqList[seqListIndex][seqLength[seqListIndex]] = y; 

(你的代码可以多,如果你使用std::vector简化。)

+0

感谢您的解决方案。我明白为什么它的工作。但不明白“抵消”的事情。 –