【LeetCode】45. Jump Game II(C++)

地址:https://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.
Example:

Input: [2,3,1,1,4]
Output: 2
Explanation: 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.

Note:

  • You can assume that you can always reach the last index.

理解:

本题要求寻找到从起点到终点的最少跳数。

实现:

使用BFS的思想,从当前位置可以跳到下一步的范围可以确定,从下一步的范围内的位置可以跳到下下一步的范围也可以确定,因此可以每次根据当前的范围判断下一步的范围。
虽然题里给出的是总是可达的,这里还是给出一种通用的方法吧,并不假设总是可达的。

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

猜你喜欢

转载自blog.csdn.net/Ethan95/article/details/85308989