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.
For example:
Given array A =
Given array A =
[2,3,1,1,4]
The minimum number of jumps to reach the last index is
Use HashSet instead of ArrayList can pass the large set of data.
2
. (Jump 1
step from index 0 to 1, then 3
steps to the last index.)Use HashSet instead of ArrayList can pass the large set of data.
public class Solution { public int jump(int[] A) { // Start typing your Java solution below // DO NOT write main() function assert (A!=null && A.length>0); int res = 0; ArrayList<Integer> toVisit = new ArrayList<Integer>(); toVisit.add(A.length-1); boolean[] visited = new boolean[A.length]; while(!toVisit.isEmpty()){ ArrayList<Integer> cur = new ArrayList<Integer>(); for(Integer temp:toVisit){ if(temp==0) return res; for(int i=0;i<A.length;i++){ if(i!=temp && !visited[i] && i+A[i]>=temp && i-A[i]<=temp){ cur.add(i); } }
visited[temp]=true;} toVisit = new ArrayList<Integer>(cur); res++; } return res; } }
No comments:
Post a Comment