来源:Leetcode
原帖:https://oj.leetcode.com/problems/jump-game-ii/
题目:
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 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)
Solution: Jump to the position where we can jump farthest (index + A[index]) next time.
代码:
原帖:https://oj.leetcode.com/problems/jump-game-ii/
题目:
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 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)
Solution: Jump to the position where we can jump farthest (index + A[index]) next time.
代码:
class Solution {
public:
// greedy method
int jump(int A[], int n) {
int start = 0, steps = 0;
while (start < n - 1) {
steps++;
if (start + A[start] >= n - 1)
return steps;
int next = start;
for (int i = start + 1; i <= start + A[start]; ++i) {
if (i + A[i] >= next + A[next])
next = i;
}
if (next == start) // cannot jump over the end
return INT_MAX;
start = next;
}
}
};
No comments:
Post a Comment