学习目标:
- 学习贪心算法
学习内容:
- 贪心算法的定义
- 如何判断能否使用贪心算法
学习时间:
- 2025-06-09 周一晚上
学习产出:
- 455.分发饼干
解题思路
本题很容易想,最大的安排即最小的浪费,即饼干应尽可能满足胃口和饼干大小差不多的人,所以对两个数组排序。如果优先考虑胃口,那么要将胃口从大到小排序,如果满足胃口小于饼干,则同时减。如果优先考虑饼干,那么饼干从小到大排序。
class Solution {
public int findContentChildren(int[] g, int[] s) {
if(g.length == 0 || s.length == 0) {
return 0;
}
Arrays.sort(g);
Arrays.sort(s);
int count = 0;
int j = s.length-1;
for (int i = g.length-1;i>=0;i--) {
if(j >= 0 && g[i] <= s[j]) {
count++;
j--;
}
}
return count;
}
}
- 376. 摆动序列
解题思路
没思路,看题解
局部最优:删除单调坡度上的节点(不包括单调坡度两端的节点),那么这个坡度就可以有两个局部峰值。
整体最优:整个序列有最多的局部峰值,从而达到最长摆动序列。
卡哥视频链接:摆动序列
class Solution {
public int wiggleMaxLength(int[] nums) {
if(nums.length == 1) {
return 1;
}
if(nums.length == 2) {
if(nums[0] != nums[1]) {
return 2;
} else {
return 1;
}
}
int result = 1 ;
int pre = 0;
for (int i = 0 ;i < nums.length -1;i++) {
int cur = nums[i+1]-nums[i];
if( (pre <= 0 && cur > 0) || (pre>=0&&cur <0)) {
result++;
pre = cur;
}
}
return result;
}
}
- 53. 最大子序和
解题思路
可以很直白的想到,如果加入下一个元素没有使得元素变负数,则可以添加,如果变成了负数,则完全清空结果集。用result来表示下标位置思路很好
class Solution {
public int maxSubArray(int[] nums) {
if (nums.length == 1){
return nums[0];
}
int sum = Integer.MIN_VALUE;
int count = 0;
for (int i = 0; i < nums.length; i++){
count += nums[i];
sum = Math.max(sum, count); // 取区间累计的最大值(相当于不断确定最大子序终止位置)
if (count <= 0){
count = 0; // 相当于重置最大子序起始位置,因为遇到负数一定是拉低总和
}
}
return sum;
}
}