Leet - 45

Having fun on Leetcode with C++, Java, Python & GO

Problem 45. Jump Game II

My attempt(s)

Code

C++

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution {
public:
    int jump(vector<int>& nums) {
        int i=0;
        int cnt=0;
        int max=0;
        int tmp=-1;
        if (nums.size()==1)
            return 0;
        if (nums[i]+i>=nums.size()-1)
            return 1;
        while (i<nums.size()-1){
            max=0;
            //cout<<"i"<<i<<endl;
            for (int j=i+1; j<=i+nums[i];j++){
                //cout<<"j"<<j<<endl;
                if (j==nums.size()-1){
                    cnt++;
                    return cnt;
                }
                    
                if ((j+nums[j])>max){
                    max=nums[j]+j;
                    //cout<<"max"<<max<<endl;
                    tmp=j;
                }                
            }
            i=tmp;
            cnt++;
            //cout<<"cnt"<<cnt<<endl;
        }
        return cnt;
    }
};

Explanation of idea

Good solution ref.

Code

Analysis

Licensed under CC BY-NC-SA 4.0