My solution about the jump game II problem with a bit explation


  • 1
    M
    public class Solution {
        public int jump(int[] nums) {
            if(nums.length==1)
                return 0;
           //main idea: every iteration pushs the reaching range to a larger range
           //when the range cover the goal index, the loop exits
           //res represents the step of the current iteration
           // head and tail control the range of every iteration
            int head=0,tail=nums[0],res=1,i,temp;
            while(tail<nums.length-1)
            {
                temp=tail;
                res++;
                for(i=head;i<=temp;i++)
                    tail=Math.max(tail,i+nums[i]);
                head=temp;
                if(tail==temp&&tail<nums.length)
                    break;
            }
            return res;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.