2017-07-31 288 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

感謝您的解決方案。我明白爲什麼它的工作。但不明白「抵消」的事情。 –