Created
February 17, 2013 15:52
-
-
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…
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #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