I have just attended a code test of some code testing site, and I think one question seems easy but I didn't get a high correctness, so if anyone can review this code snippet, I would appreciate it.
In summary:
Given an array A
, with dimension N
, 1<=N
<=100000, A[N]
within range of [-100000, 100000]. At first there is a pointer at position K
(in the beginning K=0
), and M=A[K]
, and we say the pointer will jump to position A[K+M]
, and call this a "jump of a pawn`. If at any moment, the pointer jumps out of the array, we must return the steps of jumps it takes. If it will never jump out, return -1.
class Solution {
public Solution() {}
public int solution(int[] A) {
int next = A[0] + 0;
int N = A.length;
Map<Integer, Integer> count = new HashMap<Integer, Integer>();
for (int i=0; i<N; i++) {
count.put(i, 0);
}
count.put(0, 1); //already pass position 0 once
int times = 0;
while (next < N && next >= 0) { /* next index can be negative!!!!! Error!!!! */
times ++;
next = A[next] + next;
System.out.println("Now the next index is: " + next);
if (next >= N || next < 0) { /* next index can be negative!!!!! Error!!!! */
System.out.println("Now jump out. ");
return times+1;
}
count.put(next, count.get(next) + 1);
if (count.get(next) > 1) {
System.out.println("Repeated index " + next + ", will not jump out");
return -1;
} else {
continue;
}
}
return times + 1; //edited
}
}
EDIT:
With this version I know that it is higher than 57% (original result of the quiz), but I cannot say it is 100% because I don't have all the test cases used in evaluation.
A[0] = 100000
and on the first step it jumps out of the array, your function will return2
because it executestimes ++
followed byreturn times+1
. I don't think2
is the correct answer for that case (I think it should be1
). I'm thinking that perhaps on every case you are returning a number 1 greater than the actual answer. \$\endgroup\$