title Link: https://leetcode.com/problems/jump-game-ii/?tab=DescriptionGiven an array, the values in the array represent the maximum distance at which the current position can bounce forward. Solve the minimum number of ticks required to start from subscript 0 to subscript to the last of the array! 1, when the array is empty or the array length equals 1 o'clock, do not need to bounce, so return 0 otherwise initialize step=12, initialize left=0 right = Nums[0] When left<=right into the loop body. 3. Starting from I=0, if the current bounce distance is greater than the array length, return step4, start from left and initialize to 0 for traversal, with interval of [0, right] constantly updating Max's value max = Math.max (max, left + nums[left] Note that above is left+nums[left] here is a direct representation of the position assumption moved to the i==0 subscript, relative to the i==0 can move forward distance 5, if Max's value is greater than the current right value, then update the left=right; Right=max; step++6, judging the size relationship of left and right. Repeat the 3, 4, and 5 operation reference codes above:
Packageleetcode_50;/*** * * @authorPengfei_zheng * Given array, find the minimum tick selection*/ Public classSolution45 { Public intJumpint[] nums) { if(Nums = =NULL|| Nums.length < 2) { return0; } intleft = 0; intright = Nums[0]; intStep = 1; while(Left <=Right ) { if(Right >= nums.length-1) { returnstep; } intMax =Integer.min_value; for(; left <= right; left++) {Max= Math.max (max, left +Nums[left]); } if(Max >Right ) { Left=Right ; Right=Max; Step++; } } return-1; }}
Leetcode Jump Game II (moves by array)