代码随想录算法训练营第31天|455.分发饼干、376.摆动序列、53.最大子数组和
一. 贪心算法相关题目
455.分发饼干
优先考虑饼干,小饼干先满足小胃口
思路
- 先将饼干和胃口从小到大排序
- 从小到大遍历饼干,从开始判断饼干是否满足当前孩子胃口,如果满足判断下一位孩子,并且计数加1
class Solution {
public int findContentChildren(int[] g, int[] s) {
Arrays.sort(g);
Arrays.sort(s);
int count = 0;
int start = 0;
for (int i = 0; i < s.length && start<g.length; i++) {
if (s[i]>= g[start]){ //满足第一个孩子
start++; //判断下一个
count++; //满足计数加1
}
}
return count;
}
}
优先考虑胃口大胃口对应大饼干
思路
- 分别将胃口和饼干分量排序
- 然后从大到小遍历胃口,从饼干最大开始判断是否满足当前孩子的胃口,如果满足判断下一位孩子
class Solution {
public int findContentChildren(int[] g, int[] s) {
Arrays.sort(g);
Arrays.sort(s);
int count = 0;
int start = s.length-1;
for (int i = g.length-1; i >= 0; i--) {
if (start>=0 && g[i]<= s[start]){
start -- ;
count++ ;
}
}
return count;
}
}
376.摆动序列
贪心算法
思路
- 计算序列中峰值最多的子序列
- 注意点,节点数要从1开始(默认最右边有一个峰值,数组长度为1的)
- 判断前一个高度差与当前高度差一正一负那么就是一个峰值
class Solution {
public int wiggleMaxLength(int[] nums) {
if (nums.length<=1){
return nums.length;
}
int preDiff = 0;
int curDiff = 0;
int count = 1;
for (int i = 1; i < nums.length; i++) {
curDiff = nums[i] - nums[i-1];
// 这里等于0是判断第一个峰值:prediff初始为0
if ((curDiff>0 && preDiff<=0) || (curDiff<0 && preDiff>=0)){
preDiff = curDiff;
count++;
}
}
return count;
}
}
动态规划
思路
53.最大子数组和
贪心
思路
-
遍历数组并累计数组元素,不断记录累加出的最大值,如果累加和小于等于0的话就从头计算
-
时间复杂度O(n)
-
空间复杂度O(1)
class Solution {
public int maxSubArray(int[] nums) {
int res = Integer.MIN_VALUE;
int count = 0;
for (int i = 0; i < nums.length; i++) {
count += nums[i];
if (count>res) { //取区间最大值 保证res中存放的一定是最大和
res = count;
}
if (count<=0) count = 0; //如果总和小于等于0 的话重新计算count
}
return res;
}
}