leetcode刷题笔记(Golang)--45. Jump Game II

45. 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.

BFS的解法更合理的解释

On the other hand, if we could try to understand this problem using the “BFS” concept, the thought of this solution would be quite clear. The main idea of BFS solution is: try to find the “range” which represents all the nodes can be reached in every single jump. We first define the parameter “level” to stand for the BFS level of all the jumps. Every time when we are trying to make a jump, we go through all the nodes in nums[i:preStep] and try to expand the BFS range, where “i” is the current position and “preStep” is the range generated by the previous jump. Then, we store the range in the defined parameter “curStep” and update “preStep” before we go traverse all the nodes.
func jump(nums []int) int {
	res := 0
	lg := len(nums)
	maxIndex := 0
	currIndex := 0
	for i := 0; i < lg-1; i++ {
		if i+nums[i] > maxIndex {
			maxIndex = i + nums[i]
		}
		if i == currIndex {
			res++
			currIndex = maxIndex
		}
	}
	return res   
}
发布了65 篇原创文章 · 获赞 0 · 访问量 393

猜你喜欢

转载自blog.csdn.net/weixin_44555304/article/details/104257472