Leetcode 55 - Jumping Game - Problem Solving and Analysis
<!--more-->

Topic description

Given an array of non-negative integers, you are initially at the first position of the array.

Each element in the array represents the maximum length you can jump at that position.

Determine if you can reach the last position.

  • Example 1:

    Input: [2,3,1,1,4]

    output: true

    Explanation: We can jump 1 step, from position 0 to position 1, and then jump 3 steps from position 1 to the last position.

  • Example 2:

    Input: [3,2,1,0,4]

    output: false

    Explanation: No matter what, you will always reach the position at index 3. But the maximum jump length for that position is 0, so you can never get to the last position.

submit answer

 class Solution {
    public boolean canJump(int[] nums) {
        int length = nums.length;
        int farPosition = 1;

        for (int i = 0; i < length && i < farPosition; i++) {
            if (nums[i] + i >= farPosition) {
                farPosition = nums[i] + i + 1;
            }
            if (farPosition >= length) {
                return true;
            }
        }
        return false;
    }
}

Execution time : 1 ms , beat 99.93% of users in all Java commits

Memory consumption : 41.6 MB, beats 12.50% of users across all Java commits

problem solving reflection

This problem adopts the greedy method as a whole problem-solving idea. which is:

  1. Maintain a farthest reachable location ( farPosition ).
  2. Traverse each item in the array in turn. If the index at this time is less than the farthest reachable position, that means the item can be reached, but whether it can reach the last item in the data needs to continue to judge.
  3. Determine whether the current item 索引和数值之和 is greater than the farthest reachable position, if it is greater, update the farthest reachable area to the index value and value of the current item.
  4. If the current reachable position is greater than the length of the array, it means that the last position in the array can be reached directly, and it is good to return true , otherwise, return false .

Complexity Analysis

  • Time complexity: O(n) , the worst case is to loop through all elements of the array in turn.
  • Space complexity: O(1) , record the farthest reachable position by farPosition , no additional space overhead is required.

This question is relatively simple as a whole, just summarize so much first, and continue to stick to the algorithm practice!

Source: Teamind https://teamind.co/ Welcome to reprint, please keep this statement. Thanks!

子木聊出海
1.4k 声望3.1k 粉丝

公号:「子木聊出海」