455.分发饼干
题目链接:https://leetcode.cn/problems/assign-cookies/
文档讲解:https://programmercarl.com/0455.%E5%88%86%E5%8F%91%E9%A5%BC%E5%B9%B2.html
视频讲解:https://www.bilibili.com/video/BV1MM411b7cq
思路
- 基本的思路是让大饼干优先喂饱大胃口。
- 首先对胃口和饼干都进行排序,然后从后往前进行比较,如果饼干大小大于等于胃口,
res++。 - 注意不能先遍历饼干再遍历胃口。
代码
class Solution {
public int findContentChildren(int[] g, int[] s) {
Arrays.sort(g);
Arrays.sort(s);
int res = 0;
int index = s.length - 1; // 记录饼干的下标
for (int i = g.length - 1; i >= 0; i--) { // 遍历胃口
if (index >= 0 && s[index] >= g[i]) { // 饼干大于等于胃口,就成功匹配一个
res++;
index--;
}
}
return res;
}
}
分析:时间复杂度:O(nlogn);空间复杂度:O(1)。
时间复杂度主要由排序步骤决定,其中n是g数组和s数组中的元素数量。
Arrays.sort(g);的时间复杂度为O(n log n)。Arrays.sort(s);的时间复杂度为O(n log n)。- 遍历两个数组寻找匹配的时间复杂度为
O(n)。
由于排序步骤是算法中时间复杂度最高的部分,因此整段代码的时间复杂度是O(n log n)。
376. 摆动序列
题目链接:https://leetcode.cn/problems/wiggle-subsequence/
文档讲解:https://programmercarl.com/0376.%E6%91%86%E5%8A%A8%E5%BA%8F%E5%88%97.html
视频讲解:https://www.bilibili.com/video/BV17M411b7NS
思路
本题的摆动可以分为三种情况:
- 上下有平坡
当preDiff == 0,curDiff大于或小于0时,也认为是一个摆动。
if ((preDiff >= 0 && curDiff < 0) || (preDiff <= 0 && curDiff > 0)) {
- 首尾元素
将结果res初始化为1,默认右边是有摆动的。 - 单调有平坡
当有摆动时再更新preDiff的值,而不是遍历一个元素就更新,这样就会跳过单调平坡的情况。
if ((preDiff >= 0 && curDiff < 0) || (preDiff <= 0 && curDiff > 0)) {
res++;
preDiff = curDiff;
}
代码
class Solution {
public int wiggleMaxLength(int[] nums) {
int preDiff = 0, curDiff = 0, res = 1;
for (int i = 0; i < nums.length; i++) {
if (i > 0) curDiff = nums[i - 1] - nums[i];
if ((preDiff >= 0 && curDiff < 0) || (preDiff <= 0 && curDiff > 0)) {
res++;
preDiff = curDiff;
}
}
return res;
}
}
分析:时间复杂度:O(n);空间复杂度:O(1)。
376. 摆动序列
题目链接:https://leetcode.cn/problems/maximum-subarray/
文档讲解:https://programmercarl.com/0053.%E6%9C%80%E5%A4%A7%E5%AD%90%E5%BA%8F%E5%92%8C.html
视频讲解:https://www.bilibili.com/video/BV1aY4y1Z7ya
思路
用res来记录累加的最大值。当累加和小于0时,如果它加上后面的数,就会让后面的数变小,所以这是就把sum归零,从下一个数重新寻找子序列。
代码
class Solution {
public int maxSubArray(int[] nums) {
int res = Integer.MIN_VALUE;
int sum = 0;
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
res = Math.max(res, sum);
if (sum < 0) sum = 0;
}
return res;
}
}
分析:时间复杂度:O(n);空间复杂度:O(1)。
706

被折叠的 条评论
为什么被折叠?



