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.spa
Determine if you are able to reach the last index.code
Example 1:blog
Input: [2,3,1,1,4] Output: true Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
Example 2:element
Input: [3,2,1,0,4] Output: false Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index.
解答:leetcode
經典的貪心算法,也就是每一步都求最優解,全部的最優解組合就能夠獲得整個問題的最優解。這道題關心的是最左邊的格子可否到達最右邊的格子,咱們不妨從右到左來分析,設最右邊格子的index爲lastPos,若是倒數第二個格子能夠到達lastPos,那麼更新lastPos爲倒數第二個格子的index,以此類推,若是最後但是似的lastPos爲第一個格子的index,也就是你說明該能夠從最左邊到達最右邊get
代碼以下:it
1 class Solution { 2 public: 3 bool canJump(vector<int>& nums) { 4 int lastPos = nums.size() - 1; 5 for (int i = nums.size() - 1; i >= 0; i--) 6 if (nums[i] + i >= lastPos) 7 lastPos = i; 8 return lastPos == 0; 9 } 10 };
時間複雜度:O(N)io
空間複雜度:O(1)ast
參考連接: