LeetCode solution to a problem | 45. Jump Game II (jumping game Greedy C ++)

Title Description (Difficulty)

Original title link
Here Insert Picture Description

algorithm

(greedy) THE ( n ) O (n)

Each time you update the maximum distance, then every step of the jump can range as a range, whenever i = = e n d i == end , then have to jump one step, if e n d end greater than or equal s i from e 1 size - 1 , you can exit the for loop
Note: size = direct return 0:01
Here Insert Picture Description

Time complexity is THE ( n ) O (n) , the spatial complexity is THE ( 1 ) O (1)

C ++ code

class Solution {
public:
    int jump(vector<int> &nums) {
        
        int steps = 0;
        int end = 0;
        int maxPosition = 0;
        if (nums.size() <= 1) return 0;
        for (int i = 0; i < nums.size(); i++) {
            maxPosition = max(maxPosition, i + nums[i]);
            if (i == end) {
                end = maxPosition;
                steps++;
                if (end >= nums.size() - 1) break;
            }
        }

        return steps;
    }
};

Written in the last : my blog mainly on the field of computer science summarized knowledge of thinking, and review, to write each blog it is easy to understand my goal, sharing technology and knowledge is a pleasure , and I welcome everyone together with the exchange of learning, there can be no question in the comments area, but also look forward to in-depth exchanges with your (^ ∀ ^ ●)

Published 308 original articles · won praise 149 · Views 150,000 +

Guess you like

Origin blog.csdn.net/qq_43827595/article/details/105069941