标签: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.
Your goal is to reach the last index in the minimum number of jumps.
For example:
Given array A = [2,3,1,1,4]
The minimum number of jumps to reach the last index is 2
. (Jump 1
step from index 0 to 1, then 3
steps to the last index.)
Array Greedy
... | i-1 | i |
... | 3 | 2 |
这样遍历的时间其实只有n 次,时间O(n),空间也是O(n).改进地方就是空间改O(1)。
1 #include <iostream> 2 using namespace std; 3 4 class Solution { 5 public: 6 int jump(int A[], int n) { 7 int *a = new int [n]; 8 for(int i=1;i<n;i++) 9 a[i]=INT_MAX; 10 a[0]=0; 11 int maxidx = 1; 12 for(int i=0;i<n;i++){ 13 while(maxidx<=i+A[i]&&maxidx<n){ 14 // for(int kk=0;kk<n;kk++) cout<<a[kk]<<" "; 15 // cout<<endl; 16 a[maxidx++] = a[i]+1; 17 } 18 } 19 int ret = a[n-1]; 20 delete []a; 21 return ret; 22 } 23 }; 24 25 int main() 26 { 27 int a[]={2,3,1,1,4}; 28 Solution sol; 29 cout<<sol.jump(a,sizeof(a)/sizeof(int))<<endl; 30 return 0; 31 }
1 class Solution { 2 public: 3 int jump(int A[], int n) { 4 int ret = 0; 5 int last = 0; 6 int curr = 0; 7 for (int i = 0; i < n; ++i) { 8 if (i > last) { 9 last = curr; 10 ++ret; 11 } 12 curr = max(curr, i+A[i]); 13 } 14 15 return ret; 16 } 17 };
标签:style blog http io ar color os sp for
原文地址:http://www.cnblogs.com/Azhu/p/4141896.html