Skip to content

Instantly share code, notes, and snippets.

@pdu
Created February 17, 2013 15:52
Show Gist options
  • Select an option

  • Save pdu/4971960 to your computer and use it in GitHub Desktop.

Select an option

Save pdu/4971960 to your computer and use it in GitHub Desktop.
Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Your goal is to reach the last index in the minimum number of jumps. For example: Given array A = [2,3,1,1,4] The minimum number of jumps to reach the last index is…
#include <queue>
struct Node {
int pos;
int val;
Node(int p, int v) {
pos = p;
val = v;
}
};
class Solution {
public:
int jump(int A[], int n) {
queue<Node> Q;
Q.push(Node(0, 0));
for (int i = 0; i < n; ++i) {
int val = -1;
while (Q.empty() == false) {
if (Q.front().pos >= i) {
val = Q.front().val;
break;
}
else
Q.pop();
}
if (val == -1)
return -1;
Q.push(Node(i + A[i], val + 1));
}
return Q.front().val;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment