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.
For example:
Given array A = [2,3,1,1,4]
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.)
public class Solution { public int jump(int[] A) { // Start typing your Java solution below // DO NOT write main() function int start = 0; int end = 0; int count = 0; int max = 0; int n = A.length;//forgot one element if(n == 1) return 0; while(end<n){ count++; for(int i = start; i <= end; i++){//loop i has to be less than end point not maxCover if(A[i]+i >= n-1)// forgot equal situation return count; if(A[i]+ i > max) max = A[i] + i; } start = end+1; end = max; } return -1; } }
mistake: forgot the only element and forgot when the maxcover is equal to length
Greedy: public class Solution { public int jump(int[] A) { // Start typing your Java solution below // DO NOT write main() function int maxCover = 0; int temp = 0; int count = 0; int length = A.length; for(int i = 0; i < length;){ if(temp >= length -1) break; while(i<=temp){ maxCover = Math.max(maxCover,A[i]+i); i++; } count++; temp = maxCover; } return count; } }
learned: temp 理解为一个区间,贪心找最大