LeetCode 45 Jump Game II (C++, Python)

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 = [2,3,1,1,4]
The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)


Solution 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
class Solution {
public:
    int jump(vector<int>& nums) {
        int i = 0;
        int steps = 0;
        while (i < nums.size() - 1) {
            steps ++;
            int tmp = 0;
            int reach = nums[i] + i;
            for (int j = i + 1; j <= reach; ++j) {
                if (j >= nums.size() - 1) {
                    tmp = j;
                    i = j;
                    break;
                }
                if (j + nums[j] > tmp) {
                    tmp = j + nums[j];
                    i = j;
                }
            }
            if (tmp == 0) {
                steps = numeric_limits<int>::max();
                break;
            }
        }
        return steps;
    }
};

Solution Python


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution:
    # @param {integer[]} nums
    # @return {integer}
    def jump(self, nums):
        i = 0
        steps = 0
        while i < len(nums) - 1:
            steps += 1
            tmp = 0
            reach = i + nums[i]
            for j in range(i + 1, reach + 1):
                if j >= len(nums) - 1:
                    tmp = j
                    i = j
                    break
                if j + nums[j] > tmp:
                    tmp = j + nums[j]
                    i = j
            if tmp == 0:
                steps = None
                break
        return steps;

Popular posts from this blog

How Django Works (4) URL Resolution

Python Class Method and Class Only Method

How Django Works (2) Built-in Server, Autoreload