利用stack优化, 然后每次dp的时候二分查找就好了nlgn的解法,想&写出来只需要6
const int MAXN = 1e6 + 10;
int stk_top = 0;
int dp[MAXN], stk[MAXN];
class Solution {
public:
int jump(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
dp[n - 1] = 0;
stk_top = 0;
stk[stk_top ++ ] = n - 1;
for(int i = n - 2; i >= 0; -- i){
int reach = i + A[i];
int low = 0, high = stk_top - 1, mid;
while(low <= high)
if(stk[mid = low + high >> 1] <= reach)high = mid - 1;else low = mid + 1;
if(low >= stk_top){
dp[i] = -1;
}else{
dp[i] = dp[stk[low]] + 1;
while(stk_top > 0)
if(dp[stk[stk_top - 1]] >= dp[i]) -- stk_top; else break;
stk[stk_top ++ ] = i;
}
}
return dp[0];
}
};
分钟- -