LeetCode题目链接
https://leetcode.cn/problems/assign-cookies/
https://leetcode.cn/problems/wiggle-subsequence/
https://leetcode.cn/problems/maximum-subarray/
题解
455.分发饼干
受了AI的提示,感觉就是模拟题,但是指针要回溯。题解是分开遍历饼干和胃口。
376.摆动序列
看了题解不是很懂,再看chatGPT的写法,用一个up和一个down记录波动。
https://www.bilibili.com/video/BV17M411b7NS/?vd_source=3a6627dd97ba1bc690e84872a319e5dc
看视频,视频讲的很详细。
这道题一共学会了两种解法。
啊啊啊我自己写的代码通过了,当然受AI的提示result的初始值为1,结果再+1,再根据b站视频下录友留言要去重,就加了个去重逻辑。
这一题的三种思路都值得深思。
53.最大子数组和
拿到题目第一反应是双指针法,但是这样时间复杂度肯定很高。看了题解,说这种解法勉强可以过。先用暴力写法写一遍试试。暴力解法现在不能过了,写贪心。
还有不懂的看题解,题解写的很详细。
代码
cpp
//455.分发饼干
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int findContentChildren(vector<int>& g, vector<int>& s) {
sort(g.begin(), g.end());
sort(s.begin(), s.end());
int num = 0;
for (int i = 0, j = 0;i < g.size() && j < s.size();i++, j++) {
if (s[j] >= g[i]) num++;
else i--; //重点
}
return num;
}
};
int main() {
vector<int> g1 = { 1,2,3 }, s1 = { 1,1 }, g2 = { 1,2 }, s2 = { 1,2,3 };
Solution s;
cout << s.findContentChildren(g1, s1) << endl;
return 0;
}
cpp
//376.摆动序列
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int wiggleMaxLength(vector<int>& nums) {
vector<int> tmp;
tmp.push_back(nums[0]);
for (int i = 1;i < nums.size();i++) {
if (nums[i] != nums[i - 1]) tmp.push_back(nums[i]);
}
vector<int> diff;
if (tmp.size() == 1) return 1;
if (tmp.size() == 2) return 2;
for (int i = 1; i < tmp.size(); i++) {
diff.push_back(tmp[i] - tmp[i - 1]);
}
int result = 1;
for (int i = 0; i < diff.size(); i++) {
if (i > 0 && diff[i] * diff[i - 1] < 0) result++;
}
return result + 1;
}
};
int main() {
vector<int> nums1 = { 1,7,4,9,2,5 }, nums2 = { 1,17,5,10,13,15,10,5,16,8 }, nums3 = { 1,2,3,4,5,6,7,8,9 }, nums4 = { 3,3,3,2,5 }, nums5 = { 0, 0 }, nums6 = {0, 0, 0};
Solution s;
printf("%d", s.wiggleMaxLength(nums1));
return 0;
}

cpp
//53.最大子数组和(暴力解法,不能过)
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int result = INT_MIN;
for (int i = 0;i < nums.size();i++) {
int count = 0;
for (int j = i;j < nums.size();j++) {
count += nums[j];
if (count > result) result = count;
}
}
return result;
}
};
