您的位置:首页 > 其它

[LeetCode] Jump Game II

2015-07-15 21:30 363 查看
This problem has a nice BFS structure. Let's illustrate it using the example
nums = [2, 3, 1, 1, 4]
in the problem statement. We are initially at position
0
. Then we can move at most
nums[0]
steps from it. So, after one move, we may reach
nums[1] = 3
or
nums[2] = 1
. So these nodes are reachable in
1
move. From these nodes, we can further move to
nums[3] = 1
and
nums[4] = 4
. Now you can see that the target
nums[4] = 4
is reachable in
2
moves.

Putting these into codes, we keep two pointers
start
and
end
that record the current range of the starting nodes. Each time after we make a move, update
start
to be
end + 1
and
end
to be the farthest index that can be reached in
1
move from the current
[start, end]
.

To get an accepted solution, it is important to handle all the edge cases. And the following codes handle all of them in a unified way without using the unclean
if
statements :-)

C++

class Solution {
public:
int jump(vector<int>& nums) {
int n = nums.size(), step = 0, start = 0, end = 0;
while (end < n - 1) {
step++;
int maxend = end + 1;
for (int i = start; i <= end; i++) {
if (i + nums[i] >= n - 1) return step;
maxend = max(maxend, i + nums[i]);
}
start = end + 1;
end = maxend;
}
return step;
}
};


Python

class Solution:
# @param {integer[]} nums
# @return {integer}
def jump(self, nums):
n, start, end, step = len(nums), 0, 0, 0
while end < n - 1:
step += 1
maxend = end + 1
for i in range(start, end + 1):
if i + nums[i] >= n - 1:
return step
maxend = max(maxend, i + nums[i])
start, end = end + 1, maxend
return step
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: