目录
给定一个非负整数数组 nums ,你最初位于数组的 第一个下标 。数组中的每个元素代表你在该位置可以跳跃的最大长度。
判断你是否能够到达最后一个下标。
- class Solution {
- public boolean canJump(int[] nums) {
- // 贪心算法 夸夸就是跳
- if(nums == null || nums.length == 0)
- return false;
- int reach = 0;
- int n = nums.length;
- for(int i = 0; i < nums.length; i ++){
- if(reach < i || reach >= n - 1)
- break;
- reach = Math.max(reach, i + nums[i]);
- }
- return reach >= n - 1;
- }
- }
给你一个非负整数数组 nums ,你最初位于数组的第一个位置。数组中的每个元素代表你在该位置可以跳跃的最大长度。你的目标是使用最少的跳跃次数到达数组的最后一个位置。
假设你总是可以到达数组的最后一个位置。
- class Solution {
- public int jump(int[] nums) {
- if(nums == null || nums.length == 0)
- return 0;
- int jump = 0;
- int next = 0, cur = 0;
- for(int i = 0; i < nums.length; i ++){
- //当前抵达的点小于下标,就要跳了
- if(cur < i){
- jump ++;
- cur = next; //cur更新为当前能跳到的最大值 多跳一次
- }
- //next当前能跳到的最大值
- next = Math.max(next, i + nums[i]);
- }
- return jump;
- }
- }