Leetcode45.Jump_Game_II

贪心算法
在可到达范围内,选择跳跃距离到当前点最远的位置。
时间复杂度:O(N)
C++代码:

class Solution {
public:
	int jump(vector<int>& nums) {
		if (nums.size() == 1)
			return 0;
		if (nums[0] >= nums.size() - 1)
			return 1;
		int now = 0, jump = 0, next_pos = 0;
		while (1)
		{
			for (int i = now; i <= now + nums[now]; i++)
			{
				if (nums[i] + i - now > nums[next_pos] + next_pos - now)
					next_pos = i;
			}
			jump++;
			now = next_pos;
			if (now + nums[now] >= nums.size() - 1)
				return jump + 1;
		}
	}
};

猜你喜欢

转载自blog.csdn.net/qq_42263831/article/details/82768551