455. 分发饼干
贪心算法
使用双指针,尽可能用大的饼干满足大胃口值的孩子
先对两个数组进行排序,双指针分别从后向前遍历,当s[j]能满足g[i]时,i--,j--
s[j]不能满足g[i]时,i--
class Solution {
public int findContentChildren(int[] g, int[] s) {
Arrays.sort(g);
Arrays.sort(s);
int i = g.length - 1;
int j = s.length - 1;
int res = 0;
while(i >= 0 && j >= 0){
if(s[j] >= g[i]){
res += 1;
j--;
}
i--;
}
return res;
}
}
——————————————————————————————————————————
376. 摆动序列
贪心算法
想想局部最优是什么
从前向后遍历,记录下上个差值,当当前遍历的差值与上个差值同正负时,判断哪个差值绝对值更大,就取哪个序列
当当前遍历的差值与上个差值不同正负时,将当前遍历的值加入序列中,长度加一
class Solution {
public int wiggleMaxLength(int[] nums) {
int lastDiff = 0;
int lastNum = nums[0];
int res = 1;
for (int i = 1; i < nums.length; i++) {
int nowDiff = nums[i] - lastNum;
if((lastDiff >= 0 && nowDiff < 0) || (lastDiff <= 0 && nowDiff > 0)){
lastNum = nums[i];
lastDiff = nowDiff;
res++;
}else {
lastNum = nums[i];
lastDiff = lastDiff + nowDiff;
}
}
return res;
}
}
——————————————————————————————————————————
53. 最大子数组和
贪心算法
遍历nums数组,用一个和curSum代表当前连续子数组的和,当curSum <= 0时,开启新的连续子数组。
每一次遍历更新一次最大和
class Solution {
public int maxSubArray(int[] nums) {
//贪心做法
//int max = Integer.MIN_VALUE;
//int curSum = 0;
//
//for (int i = 0; i < nums.length; i++) {
// if(curSum <= 0){
// curSum = nums[i];
// }else {
// curSum += nums[i];
// }
// max = Math.max(max, curSum);
//}
//return max;
//动态规划做法
//dp[i]表示以nums[i]为结尾的连续子数组的最大和
int[] dp = new int[nums.length];
dp[0] = nums[0];
int res = dp[0];
for (int i = 1; i < nums.length; i++){
dp[i] = Math.max(dp[i - 1] + nums[i], nums[i]);
res = Math.max(res, dp[i]);
}
return res;
}
}