分发饼干
题目链接:力扣
我的思路是,先将饼干的尺寸和小孩的胃口从小到大做排序。
然后,将小饼干分给胃口小的小孩 ,若当前饼干的尺寸不能满足小孩的胃口,则指向饼干数组的指针自加,若能满足,则指向饼干的指针和指向小孩的指针同时自加。
class Solution {
public:
int findContentChildren(vector<int>& g, vector<int>& s) {
sort(g.begin(),g.end()); //胃口
sort(s.begin(),s.end()); //尺寸
int gIndex = 0;
int sIndex = 0;
int result = 0;
while(gIndex < g.size() && sIndex < s.size())
{
if(s[sIndex] >= g[gIndex])
{
sIndex++;
gIndex++;
result++;
}
else
sIndex++;
}
return result;
}
};
摆动序列
题目链接:力扣
关于这道题的思路,看到卡哥画的这张图就能够很快理解了
局部最优:删除单调坡度上的节点(不包括单调坡度两端的节点),那么这个坡度就可以有两个局部峰值。整体最优:整个序列有最多的局部峰值,从而达到最长摆动序列。
class Solution {
public:
int wiggleMaxLength(vector<int>& nums) {
if(nums.size() <= 1)
return nums.size();
int index = 0;
int isPos = 0;
while(index < nums.size()-1)
{
if(nums[index+1] == nums[index])
index++;
else if(nums[index+1] > nums[index])
{
isPos = 1; index++; break;
}
else if(nums[index+1] < nums[index])
{
isPos = 0; index++; break;
}
}
int Result = nums[index] == nums[index-1] ? 1:2;
while(index < nums.size()-1)
{
if(isPos && nums[index+1] - nums[index] >= 0) //上两个数差为正,与下个数差也为正
{
index++;
}
else if(isPos && nums[index+1] - nums[index] < 0) //上两个数差为正,与下个数差为负
{
isPos = 0;
Result++;
index++;
}
else if(!isPos && nums[index+1] - nums[index] > 0) //上两个数差为负,与下个数差为正
{
isPos = 1;
Result++;
index++;
}
else if(!isPos && nums[index+1] - nums[index] <= 0) 上两个数差为负,与下个数差也为负
{
index++;
}
}
return Result;
}
};
最大子序和
题目链接:力扣
局部最优:当前“连续和”为负数的时候立刻放弃,从下一个元素重新计算“连续和”,因为负数加上下一个元素 “连续和”只会越来越小。
全局最优:选取最大“连续和”
从代码角度上来讲:遍历 nums,从头开始用 count 累积,如果 count 一旦加上 nums[i]变为负数,那么就应该从 nums[i+1]开始从 0 累积 count 了,因为已经变为负数的 count,只会拖累总和。
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int index = 0;
int sum = 0;
int max = INT_MIN;
while(index < nums.size())
{
sum += nums[index];
if(sum > max) max = sum;
if(sum <= 0) sum = 0;
index++;
}
return max;
}
};