贪心练习题
1.题目描述
给你一个非负整数数组 nums
,你最初位于数组的 第一个下标 。数组中的每个元素代表你在该位置可以跳跃的最大长度。
判断你是否能够到达最后一个下标,如果可以,返回 true
;否则,返回 false
。
示例 1:
1 2 3
| 输入:nums = [2,3,1,1,4] 输出:true 解释:可以先跳 1 步,从下标 0 到达下标 1, 然后再从下标 1 跳 3 步到达最后一个下标。
|
示例 2:
1 2 3
| 输入:nums = [3,2,1,0,4] 输出:false 解释:无论怎样,总会到达下标为 3 的位置。但该下标的最大跳跃长度是 0 , 所以永远不可能到达最后一个下标。
|
提示:
- $1 <= nums.length <= 10^4$
- $0 <= nums[i] <= 10^5$
2.题解
2.1 贪心算法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| class Solution { public boolean canJump(int[] nums) { int cover = 0; for (int i = 0; i <= cover; i++) { cover = Math.max(i + nums[i], cover); if (cover >= nums.length - 1) return true; } return false; } }
|
1.题目描述
给定一个长度为 n
的 0 索引整数数组 nums
。初始位置为 nums[0]
。
每个元素 nums[i]
表示从索引 i
向前跳转的最大长度。换句话说,如果你在 nums[i]
处,你可以跳转到任意 nums[i + j]
处:
0 <= j <= nums[i]
i + j < n
返回到达 nums[n - 1]
的最小跳跃次数。生成的测试用例可以到达 nums[n - 1]
。
示例 1:
1 2 3 4
| 输入: nums = [2,3,1,1,4] 输出: 2 解释: 跳到最后一个位置的最小跳跃数是 2。 从下标为 0 跳到下标为 1 的位置,跳 1 步,然后跳 3 步到达数组的最后一个位置。
|
示例 2:
1 2
| 输入: nums = [2,3,0,1,4] 输出: 2
|
提示:
- $1 <= nums.length <= 10^4$
0 <= nums[i] <= 1000
- 题目保证可以到达
nums[n-1]
2.题解
2.1 贪心算法-写法1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| class Solution { public int jump(int[] nums) { if (nums.length == 1) return 0; int curDistance = 0; int count = 0; int nextDistance = 0; for (int i = 0; i < nums.length; i++) { nextDistance = Math.max(i + nums[i], nextDistance); if (i == curDistance) { count++; curDistance = nextDistance;
if (nextDistance >= nums.length - 1) break; } } return count; } }
|
2.2 贪心算法-写法2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| class Solution { public int jump(int[] nums) { int result = 0; int curDistance = 0; int nextDistance = 0;
for (int i = 0; i < nums.length - 1; i++) { nextDistance = Math.max(i + nums[i], nextDistance);
if (i == curDistance) { result++; curDistance = nextDistance; } }
return result; } }
|