Jump Game II

描述

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.)

分析

贪心法。

代码1

  1. // LeetCode, Jump Game II
  2. // 时间复杂度O(n),空间复杂度O(1)
  3. class Solution {
  4. public:
  5. int jump(const vector<int>& nums) {
  6. int step = 0; // 最小步数
  7. int left = 0;
  8. int right = 0; // [left, right]是当前能覆盖的区间
  9. if (nums.size() == 1) return 0;
  10. while (left <= right) { // 尝试从每一层跳最远
  11. ++step;
  12. const int old_right = right;
  13. for (int i = left; i <= old_right; ++i) {
  14. int new_right = i + nums[i];
  15. if (new_right >= nums.size() - 1) return step;
  16. if (new_right > right) right = new_right;
  17. }
  18. left = old_right + 1;
  19. }
  20. return 0;
  21. }
  22. };

代码2

  1. // Jump Game II
  2. // 时间复杂度O(n),空间复杂度O(1)
  3. class Solution {
  4. public:
  5. int jump(const vector<int>& nums) {
  6. int result = 0;
  7. // the maximum distance that has been reached
  8. int last = 0;
  9. // the maximum distance that can be reached by using "ret+1" steps
  10. int cur = 0;
  11. for (int i = 0; i < nums.size(); ++i) {
  12. if (i > last) {
  13. last = cur;
  14. ++result;
  15. }
  16. cur = max(cur, i + nums[i]);
  17. }
  18. return result;
  19. }
  20. };

相关题目

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/cpp/greedy/jump-game-ii.html