贪心算法,你想先喂哪个小孩?| LeetCode:455.分发饼干_哔哩哔哩_bilibili
class Solution {
public:
int findContentChildren(vector<int>& g, vector<int>& s) {
sort(g.begin(),g.end());
sort(s.begin(),s.end());
int index=s.size()-1;
int result=0;
for(int i=g.size()-1;i>=0;i--)
{
if(index>=0&&s[index]>=g[i])
{
result++;
index--;
}
}
return result;
}
};
贪心算法,寻找摆动有细节!| LeetCode:376.摆动序列_哔哩哔哩_bilibili
通过记录峰值,并考虑三种特殊情况 首尾 平坡 单调平坡
class Solution {
public:
int wiggleMaxLength(vector<int>& nums) {
if(nums.size()==1)
return 1;
int prediff=0;
int curdiff=0;
int result=1;
for(int i=0;i<nums.size()-1;i++)
{
curdiff=nums[i+1]-nums[i];
if((prediff>=0&&curdiff<0)||(prediff<=0&&curdiff>0))
{
result++;
prediff=curdiff;
}
}
return result;
}
};
贪心算法的巧妙需要慢慢体会!LeetCode:53. 最大子序和_哔哩哔哩_bilibili
连续和小于0就抛弃
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int result=INT_MIN;
int count=0;
for(int i=0;i<nums.size();i++)
{
count+=nums[i];
if(count>result)
result=count;
if(count<0)
count=0;
}
return result;
}
};