Day31 贪心算法

Day31 贪心算法

455.分发饼干

我的思路:

小孩数组g指针一直前移,只有饼干数组s满足条件时,才前移,并且更新num

解答:

java 复制代码
class Solution {
    public int findContentChildren(int[] g, int[] s) {
        Arrays.sort(g);
        Arrays.sort(s);
        int num = 0;
        for(int i = g.length - 1, j = s.length - 1; i >= 0 && j >= 0; i--) {
            if(g[i] <= s[j]) {
                num += 1;
                j --;
            }
        }
        return num;
    }
}

376. 摆动序列

我的思路:

将数组分为length<2和>=2考虑;

=2时,先判断前两个是否为摆动,是则初始化count = 2,否则初始化count = 1;然后从i = 2,(第三个数字)开始统计count

<2的话,直接返回数组长度length

解答:

java 复制代码
class Solution {
    public int wiggleMaxLength(int[] nums) {
        if(nums.length < 2) {
            return nums.length;
        }
        int count = 1;
        int prediff = nums[1] - nums[0];
        if(prediff != 0) {
            count = 2;
        }
        for(int i = 2; i < nums.length; i++) {
            int diff = nums[i] - nums[i-1];
            if((diff > 0 && prediff <= 0) || (diff < 0 && prediff >= 0)) {
                count ++;
                prediff = diff;
            }
        }
        return count;
    }
}

53. 最大子序和

我的思路:

用一个同样大小的数组存储遍历到目前的最大连续数组之和,如果遍历到的元素大于之前的数组之和,则进行更新

解答:

java 复制代码
class Solution {
    public int maxSubArray(int[] nums) {
        if(nums == null || nums.length == 0) {
            return 0;
        }
        int[] res = new int[nums.length];
        res[0] = nums[0];
        int maxnum = res[0];
        for(int i = 1; i < nums.length; i++) {
            res[i] = Math.max(res[i-1] + nums[i], nums[i]);
            maxnum = Math.max(res[i], maxnum);
        }
        return maxnum;
    }
}
相关推荐
小比卡丘1 小时前
C语言进阶版第17课—自定义类型:联合和枚举
android·java·c语言
一个不知名程序员www1 小时前
leetcode第189题:轮转数组(C语言版)
c语言·leetcode
xmh-sxh-13141 小时前
java 数据存储方式
java
liu_chunhai1 小时前
设计模式(3)builder
java·开发语言·设计模式
一叶祇秋2 小时前
Leetcode - 周赛417
算法·leetcode·职场和发展
ya888g2 小时前
GESP C++四级样题卷
java·c++·算法
【D'accumulation】2 小时前
令牌主动失效机制范例(利用redis)注释分析
java·spring boot·redis·后端
小叶学C++2 小时前
【C++】类与对象(下)
java·开发语言·c++
2401_854391082 小时前
高效开发:SpringBoot网上租赁系统实现细节
java·spring boot·后端
Cikiss2 小时前
微服务实战——SpringCache 整合 Redis
java·redis·后端·微服务