Face questions
This question faces very simple, easy to understand. Given non-negative group, each element can be regarded as a lattice. Wherein each element value represents the number of grid current can jump, can reach a final determination whether the grid.
Sample
Input: [2,3,1,1,4] Output: true Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.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.
algorithm
As long as there is a path to reach the final it will be explained. We can look forward from the back, as long as there front element index plus its element value is greater than the target element index value , on behalf of the lattice can jump from the previous target grid. As long as we move forward to meet the judge from sliding forward on the condition that the target grid in front of the grid to be updated until the array represents the head can go through; otherwise, a dead end.
Flashback through the array, the array is defined as the target tail, the element value is determined an index value +> target? The target = index: no treatment;
Convenience ends, the determination target = 0 true:? False
Evaluation
Time complexity: O (n) only needs to traverse the primary array.
Space complexity: O (1)
Source
1 class Solution { 2 public: 3 bool canJump(vector<int>& nums) { 4 int len = nums.size(); 5 if(len <= 1) 6 return true; 7 8 int target = len -1; 9 for(int i = target-1; i >= 0; i--) 10 { 11 if(nums[i] + i >= target) 12 target = i; 13 } 14 15 return target == 0; 16 } 17 };