标签:style blog http io ar color os sp for
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
.
Array Greedy
我写的如下:
1 #include <iostream> 2 using namespace std; 3 4 class Solution { 5 public: 6 bool canJump(int A[], int n) { 7 if(n<=1) return true; 8 int last = 1; 9 for(int i =0;i<last&&i<n;i++){ 10 last = last>i+A[i]+1?last:i+A[i]+1; 11 if(last>=n) return true; 12 } 13 return false; 14 } 15 }; 16 17 int main() 18 { 19 int A[] = {3,2,1,0,4}; 20 Solution sol; 21 cout<<sol.canJump(A,sizeof(A)/sizeof(int))<<endl; 22 return 0; 23 }
1 #include <iostream> 2 using namespace std; 3 4 /**class Solution { 5 public: 6 bool canJump(int A[], int n) { 7 if(n<=1) return true; 8 int last = 1; 9 for(int i =0;i<last&&i<n;i++){ 10 last = last>i+A[i]+1?last:i+A[i]+1; 11 if(last>=n) return true; 12 } 13 return false; 14 } 15 }; 16 */ 17 class Solution { 18 public: 19 bool canJump(int A[], int n) { 20 for(int i = n-2; i >= 0; i--){ 21 if(A[i] == 0){ 22 int j; 23 for(j = i - 1; j >=0; j--){ 24 if(A[j] > i - j) break; 25 } 26 if(j == -1) return false; 27 } 28 } 29 return true; 30 } 31 }; 32 33 int main() 34 { 35 int A[] = {3,2,1,1,4}; 36 Solution sol; 37 cout<<sol.canJump(A,sizeof(A)/sizeof(int))<<endl; 38 return 0; 39 }
标签:style blog http io ar color os sp for
原文地址:http://www.cnblogs.com/Azhu/p/4127612.html