贪心算法
思路:优先把最大的饼干分配给胃口最大的人,然后将两个数组都从后往前遍历
代码:
class Solution {
public:
int findContentChildren(vector<int>& g, vector<int>& s) {
sort(g.begin(),g.end());
sort(s.begin(),s.end());
int num = s.size()-1;
int res = 0;
for(int i = g.size() - 1;i >= 0;i--)
{
if(num >= 0 && s[num] >= g[i] )
{
res++;
num--;
}
}
return res;
}
};
思路:遍历一遍数组,并且比较相邻的差值,需要判断三次不同的平坡情况
代码:
class Solution {
public:
int wiggleMaxLength(vector<int>& nums) {
if (nums.size() <= 1) return nums.size();
int res = 1;
int diff = nums[1] - nums[0];
if(diff != 0) res = 2;//如果第一二个数的差不为0,则序列长度为2
for(int i = 2;i <= nums.size() - 1;i++)
{
int currentdiff = nums[i] - nums[i - 1];
if((currentdiff > 0 && diff <= 0) || (currentdiff < 0 && diff >= 0))//当差值从正数转为负数或从负数转为正数
{
res++;
diff = currentdiff;
}
}
return res;
}
};
思路:使用动态规划的思想,从第一个数开始,往后遍历数组,每次加上一个遍历得到的数,然后max取最大值
代码:
class Solution {
public:
int maxSubArray(vector<int>& nums) {
if(nums.empty()) return 0;
int cur = nums[0];
int res = nums[0];
for(int i = 1;i < nums.size();i++)
{
cur = max(nums[i],cur + nums[i]);
res = max(res,cur);
}
return res;
}
};