【LeetCode刷题日志】:分发饼干、摆动序列

94 阅读1分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第14天,点击查看活动详情

1、写在前面

大家好,这里是【LeetCode刷题日志】。今天的两道题分别是:

  • 分发饼干
  • 摆动序列

2、内容

2.1、题目一:分发饼干

链接:455. 分发饼干 - 力扣(LeetCode)

(1) 描述

image.png

(2) 举例

image.png

image.png

(3) 解题

贪心

class Solution {
public:
    int findContentChildren(vector<int>& g, vector<int>& s) {
        // 先排序 g 和 s 
        sort(g.begin(),g.end());
        sort(s.begin(),s.end());
        // 可以满足小孩胃口的数量
        int count = 0;
        // 遍历饼干尺寸数组 s
        for(int i = 0; i < s.size(); ++i) {
            // 如果饼干尺寸 大于 小孩的尺寸,则表示满足该小孩,count加一
            if( count < g.size() && s[i] >= g[count] ){
                count++;
            }
        }
        // 最后返回结果
        return count;
    }
};

2.2、题目二:摆动序列

链接:376. 摆动序列 - 力扣(LeetCode)

(1) 描述

image.png

(2) 举例

image.png

image.png

image.png

(3) 解题

贪心

class Solution {
public:
    int wiggleMaxLength(vector<int>& nums) {
        if(nums.size() <= 1) return nums.size();
        int up = 1;
        int down = 1;
        for(int i = 1; i<nums.size(); i++) {
            if(nums[i-1] < nums[i]) {
                // 如果前一个元素小于后一个元素(递增),则更新up
                up = down + 1;
            }
            if(nums[i-1] > nums[i]) {
                // 如果前一个元素大于后一个元素(递减),则更新down
                down = up + 1;
            }
        }
        return max(up, down);
    }
};

摆动序列.gif

3、写在最后

好的,今天就先刷到这里。