首页 > 技术文章 > jump game(贪心算法)

yuanninesuns 2018-03-09 20:59 原文

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.Determine if you are able to reach the last index.

 1 #include<iostream>
 2 #include<vector>
 3 #include<Windows.h>
 4 using namespace std;
 5 class Solution {
 6 public:
 7     bool canJump(vector<int>& nums) {
 8         int lar = 0;
 9         int i = 0;
10         for (i = 0; i < nums.size() && i<=lar; i++) {
11             lar = max(nums[i] + i, lar);
12         }
13         return i == nums.size();
14     }
15 
16     bool canJump2(vector<int>& nums) {
17         int overflow = 0; // 当前可以覆盖到的下标
18         for (int i = 0; i < nums.size() - 1; i++) {
19             if (overflow < i) { return false; }  // 提前中断, 走不下去了
20             int k = i + nums[i];
21             if (k > overflow) { overflow = k; }
22         }
23         return overflow >= nums.size() - 1;
24     }
25 };

 

推荐阅读