贪心的本质是选择每一阶段的局部最优,从而达到全局最优
贪心算法一般分为如下四步:
感觉还没背熟,要多刷这个章节
- class Solution {
- public int findContentChildren(int[] g, int[] s) {
- Arrays.sort(g);
- Arrays.sort(s);
- int res = 0;
- int idx = s.length - 1;
- //遍历胃口
- for (int i =g.length - 1; i >= 0; i--) {
- if (idx >= 0 && s[idx] >= g[i]) {
- res++;
- idx--;
- }
- }
- return res;
- }
- }
三种情况:
1. 上下坡中有平坡
2. 数组首尾两端
3. 单调坡中有平坡
- class Solution {
- public int wiggleMaxLength(int[] nums) {
- if (nums.length <= 1) return nums.length;
- int cur = 0;
- int pre = 0;
- int res = 1;
-
- for (int i = 0; i < nums.length - 1; i++) {
- cur = nums[i + 1] - nums[i];
- //出现峰值
- if (pre <= 0 && cur > 0 || pre >= 0 && cur < 0) {
- res++;
- pre = cur;
- }
- }
- return res;
- }
- }
- class Solution {
- public int maxSubArray(int[] nums) {
- int maxToCur = nums[0];
- int sum = nums[0];
-
- for (int i = 1; i < nums.length; i++) {
- maxToCur = Math.max(maxToCur + nums[i], nums[i]);
- sum = Math.max(maxToCur, sum);
- }
- return sum;
- }
- }