1.盛最多水得容器
题目链接:力扣
思路:使用双指针从数组两端开始遍历,因为盛水量取决于底边长和两块木板中较短的那一块,所以需要尽可能改变较短木板的长度,为何不移动较长的木板,因为即使移动后的木板比原来长,盛水量还是取决于最短木板,所以是该变最短木板。移动后底边长减小,最短木板增减性不确定,所以可以用max记录最大值,每次比较当前盛水量
代码实现:
class Solution
{
public:
int maxArea(vector<int>& height)
{
int max = 0, volume;
int i = 0, j = height.size() - 1;
while (i <= j)
{
volume = min(height[i], height[j]) * (j - i);
if (volume > max)
{
max = volume;
}
if (height[i] < height[j])
{
i++;
}
else
{
j--;
}
}
return max;
}
};
总结:贪心算法需要划分问题规模,选出当前的最优解,而此题最优解策略是:求出当前盛水量->与最大盛水量比较->增加最短木板的长度->求出当前盛水量->与最大盛水量比较...
2.跳跃游戏
题目链接:力扣
思路:一开始思路一直停留在模拟是否可以跳到,后来发现很难写,写出来也会有很多判断语句和个别未通过测试点,后来翻了一下题解,题解的思路是不断更新从第一个数字开始能跳的最远的距离,如果出现数组下标大于能跳的最远距离,那么就一定跳不到(也就是说中间一定出现了停在1的时候)
代码实现:
class Solution
{
public:
bool canJump(vector<int>& nums)
{
int max_jump = 0;
for (int i = 0; i < nums.size(); i++)
{
if (i > max_jump)
{
return false;
}
max_jump = max(max_jump, i + nums[i]);
}
return true;
}
};
3.买卖股票的最佳时机2
题目链接:力扣
思路:题意是在一段时间内获得最大利润,按照贪心算法,可以思考:只要今天价格比明天低,那我就今天买明天卖,如果明天价格比后天低,那我也可以明天重新买入,后天卖出,按照此思路书写代码
class Solution
{
public:
int maxProfit(vector<int>& prices)
{
int profit = 0;
for (int i = 1;i < prices.size();i++)
{
if (prices[i] > prices[i - 1])
{
profit += (prices[i] - prices[i - 1]);
}
}
return profit;
}
};
4.加油站
题目链接:力扣
代码实现:
class Solution
{
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost)
{
int rest = 0, run = 0, start = 0;
for (int i = 0; i < gas.size(); i++)
{
run += (gas[i] - cost[i]);
rest += (gas[i] - cost[i]);
//rest变量为走完全程时油箱内剩余的油量
//如果rest最终小于0,即总体上加的油比路程花费的少,那么永远都到不了
if (run < 0)//如果run小于0,那么代表当前这个点走不到下一个点,可以从下一个点开始模拟
{
start = i + 1;
run = 0;
}
}
//判断最后的rest,如果小于0,那么无论哪里都走不了循环
//如果大于0,肯定是可以走一个循环的
return rest < 0 ? -1 : start;
}
};