算法刷题记录 Day28
Date: 2024.03.23
lc 45. 跳跃游戏II
// 使用范围计算
class Solution {
public:int jump(vector<int>& nums) {if(nums.size() == 1)return 0;int pre_range = 0;int range = 0; // 当前覆盖范围int cur_steps = 0; // 当前步数// 每次遍历当前范围较上轮范围的增量,步数加一。while(range < nums.size()){int tmp_range = range;for(int i=pre_range; i<=tmp_range && i<nums.size(); i++){range = max(range, i+nums[i]);}cur_steps++;pre_range = tmp_range;if(range >= nums.size()-1)break;}return cur_steps;}
};// 暴力,记录到达每个点的最小步数
class Solution {
public:int jump(vector<int>& nums) {if(nums.size() == 1)return 0;vector<int> canRearch(nums.size(), -1); //-1表示不可达,反之则表示到达所需最少步数canRearch[0] = 0;for(int i=0; i<nums.size(); i++){int len = nums[i];if(canRearch[i] != -1){for(int j=i+1; j<=i+len && j<nums.size(); j++){if(canRearch[j] == -1)canRearch[j] = canRearch[i] + 1;else{canRearch[j] = min(canRearch[j], canRearch[i]+1);}}}}return canRearch[nums.size()-1];}
};
lc 55. 跳跃游戏
// 优化:取能覆盖的最大值,而不是按每个位置更新
class Solution {
public:bool canJump(vector<int>& nums) {// 找到所有能到达终点的前继点int range = 0;for(int i=0; i<nums.size() && i<=range; i++){int len = nums[i];range = max(range, i+len);//cout<<"i:"<<i<<" range:"<<range<<endl;}return range >= (nums.size()-1);}
};// 暴力
class Solution {
public:bool canJump(vector<int>& nums) {// 从头往后推能到达的位置vector<bool> canRearch(nums.size(), false);canRearch[0] = true;for(int i=0; i<nums.size(); i++){int len = nums[i];if(canRearch[i]){ //若该位置能到达,根据该位置的长度,更新一轮能到达位置for(int j=i+1; j<=i+len && j<nums.size(); j++){canRearch[j] = true;}}}return canRearch[nums.size()-1];}
};
lc 122. 买卖股票的最佳时机II
class Solution {
public:int maxProfit(vector<int>& prices) {int earn = 0; //当前利润// 后一天比当前贵,不卖;后一天比当前便宜,卖;for(int i=0; i<prices.size()-1; i++){if(prices[i+1] > prices[i])earn += (prices[i+1] - prices[i]);}return earn;}
};