1. 程式人生 > >LeetCode --- 55. Jump Game

LeetCode --- 55. Jump Game

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.

For example:

A = [2,3,1,1,4], return true. 
A = [3,2,1,0,4], return false. 

這道題的要求是給定一整數陣列,陣列元素表示每次可以跳躍的最大距離。然後初始位置在陣列的第一個元素,返回能否數到達最後元素。

採用貪心的思路,採用reach變數維護能到達最遠處,即為全域性最優解。當遍歷到i的時候,區域性最優解為A[i]+i,因此,此時的全域性最優解即為reach和A[i]+i的最大值:reach = max(reach, A[i] + i)。

還有Jump Game II這道題,是這題的提升,需要計算到達最後元素時的最小步數。

時間複雜度:O(n)

空間複雜度:O(1)

 1 class Solution
 2 {
 3 public:
 4     bool canJump
(int A[], int n) 5 { 6 int reach = 0; 7 for(int i = 0; i <= reach && i < n; ++ i) 8 reach = max(reach, A[i] + i); 9 10 return reach >= n - 1; 11 } 12 };