題目描述
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.
Example:
Input: [2,3,1,1,4]
Output: 2
Explanation: 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.
Note:
You can assume that you can always reach the last index.
給定一個(gè)非負(fù)整數(shù)數(shù)組,你最初位于數(shù)組的第一個(gè)位置。
數(shù)組中的每個(gè)元素代表你在該位置可以跳躍的最大長(zhǎng)度。
你的目標(biāo)是使用最少的跳躍次數(shù)到達(dá)數(shù)組的最后一個(gè)位置。
題解
首先想到的解法是:聲明一個(gè)數(shù)組dp(size, size), dp[i]表示達(dá)到坐標(biāo)i的最小跳數(shù)。
使用雙層循環(huán),第一層遍歷數(shù)組,第二層在nums[i]范圍內(nèi)遍歷,表示在i的可及范圍內(nèi)進(jìn)行更新dp[i+j], dp[i+j]=min(dp[i+j], dp[i]+1);但是要保證i+j的有效性。一旦i+j == size-1,及時(shí)終止循環(huán)。
代碼:
class Solution {
public:
int jump(vector<int>& nums) {
int size = nums.size();
vector<int> dp(size, size);
dp[0] = 0;
for (int i=0; i< size; i++){
for (int j=1; j<=nums[i] && i+j<size; j++){
dp[i+j] = min(dp[i+j], dp[i]+1);
if (i+j == size-1) break;
}
}
return dp[size-1];
}
};
這種方法對(duì)于一般的測(cè)試集能通過(guò),對(duì)于特別變態(tài)的,2500-0的數(shù)組會(huì)導(dǎo)致超時(shí)【ps:可以針對(duì)這個(gè)測(cè)試用例單獨(dú)處理,能accept;畢竟不符合題意,時(shí)間復(fù)雜度太高】。
另一種方法和這個(gè)方法類似:不使用雙層循環(huán)。使用兩個(gè)變量cur, next分別表示當(dāng)前窗口的右邊界,下個(gè)窗口的右邊界;遍歷數(shù)組時(shí),不斷更新next窗口的右邊界;當(dāng)當(dāng)前位置i超出當(dāng)前窗口的右邊界時(shí),更新cur,更新jumps。循環(huán)結(jié)束,返回jumps;或者當(dāng)更新cur>=size-1數(shù)組邊界時(shí),即使返回。
代碼:
class Solution {
public:
int jump(vector<int>& nums) {
int size = nums.size(), cur = 0, next = 0, jumps = 0;
for (int i=0; i< size; ++i){
if (i > cur){
cur = next;
++jumps;
// if (cur >= size-1) break;
}
next = max(next, i + nums[i]);
}
return jumps;
}
};
Reference
https://www.cnblogs.com/grandyang/p/4373533.html