LeetCode [45] Jumper II (greedy)

The title 45 selected LeetCode title Jumper II , implemented using the greedy algorithm.

Title Description

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: Suppose you can always reach the last position of the array.

Problem solution ideas

Jumping game

  1. Analysis question are intended: Each element in the array represents the maximum jump length you can in this position, i.e. the position i, the number of steps can be jump [0, nums [i]]
  2. Greedy idea: every jump record jump the farthest are the number of (current best) step
  3. Record number: iterate, if the current position if i is equal to the current position arrived reach, then jump again steps ++

Implementation code

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

II

Published 49 original articles · won praise 15 · views 10000 +

Guess you like

Origin blog.csdn.net/xiaoma_2018/article/details/103555035