C ++ algorithms: greedy algorithm jumping game -----

topic:

Given a non-negative integer array, you initially located in the first position of the array. Each element in the array represents the maximum length you can jump in that position. Your goal is to use the least number of hops to reach the last position of the array.

Example:

Input: [2,3,1,1,4]
Output: 2
Explanation: minimum number of hops jump to the last position is 2.
Jump from index 0 to index the position of 1, 1-step jump, jump and then step 3 reaches the last position of the array.

Description:

Assuming you can always reach the last position of the array.

Ideas; (each step must jump, then find each step can jump the farthest distance)

Can take advantage of the current hop hop hop can determine the scope of a range, the next time jump range over nums.size () - 1, the end!
Because the number of hops rather than jumping path of the request, the range can be determined directly next hop!
I + 1-hop range: the i-th hop of the maximum distance i + 1 ~ hops up to each point in the farthest distance.
Each access point only once, the time complexity of o (n), the spatial complexity o (1)

Code;

class Solution {
public:
    int jump(vector<int>& nums) {
        if(nums.size()<=1) return 0;
        int step=0, start=0,reach=0;
        while( reach <nums.size()-1 ){
            int farest=0;
            for(int i=start; i<=reach; ++i)
                farest=max(farest,i+nums[i]);
            start=reach+1;
            reach=farest;
            step++;
        }
        return step;
    }
};

Guess you like

Origin blog.csdn.net/qq_31820761/article/details/91861869