Leetcode45:
题目描述:
给定一个长度为 n
的 0 索引整数数组 nums
。初始位置为 nums[0]
。
每个元素 nums[i]
表示从索引 i
向前跳转的最大长度。换句话说,如果你在 nums[i]
处,你可以跳转到任意 nums[i + j]
处:
0 <= j <= nums[i]
i + j < n
返回到达 nums[n - 1]
的最小跳跃次数。生成的测试用例可以到达 nums[n - 1]
。
代码及注释解析:
class Solution {
public:
int jump(vector<int>& nums) {
int n=nums.size();
int ans=0;
int start=0;
//跳跃一次所能到达的最大下标,一次不代表跳一步
//从下标i跳一次包含了 [1,nums[i]]这个跳跃长度
int end=0;
//直到能跳到终点
while(end<nums.size()-1){
int maxStep=0;
//查找在跳跃区间可跳的最大范围
for(int i=start;i<=end;i++){
maxStep=max(maxStep,i+nums[i]);
}
//更新下一次跳跃区间
start=end;
end=maxStep;
//跳了一次
ans++;
}
return ans;
}
};
Leetcode55:
题目描述:
给你一个非负整数数组 nums
,你最初位于数组的 第一个下标 。数组中的每个元素代表你在该位置可以跳跃的最大长度。
判断你是否能够到达最后一个下标,如果可以,返回 true
;否则,返回 false
。
代码及注释解析:
class Solution {
public:
bool canJump(vector<int>& nums) {
//能到达的最远下标
int k=0;
for(int i=0;i<nums.size();i++){
//当前位置大于k了,说明不能跳到该位置
if(i>k)return false;
//更新能跳的最远下标
k=max(k,i+nums[i]);
}
return true;
}
};
Leetcode122:
题目描述:
给你一个整数数组 prices
,其中 prices[i]
表示某支股票第 i
天的价格。
在每一天,你可以决定是否购买和/或出售股票。你在任何时候 最多 只能持有 一股 股票。你也可以先购买,然后在 同一天 出售。
返回 你能获得的 最大 利润 。
代码及注释解析:
class Solution {
public:
int maxProfit(vector<int>& prices) {
int n=prices.size();
int ans=0;
//遍历一遍股票增长趋势
//只在增长的一天买入,下一天卖出即能达到最大利润
for(int i=1;i<n;i++){
//每次只找股票增长的一天出售
if(prices[i]>prices[i-1])ans+=prices[i]-prices[i-1];
}
return ans;
}
};