45. Jump Game II

BFS & Greedy

class Solution {
    public int jump(int[] nums) {
        // result
        int count = 0;
        // the last index of next layer;
        int nextEnd = 0;
        // the last index of current layer;
        int currentEnd = 0;
        for(int i =0; i<nums.length-1; i++){
            nextEnd = i+nums[i]>nextEnd? i+nums[i]: nextEnd;
            if (i==currentEnd){
                count++;
                currentEnd = nextEnd;
            }
        }
        return count;
    }
}

Last updated