Day31 贪心算法

Day31 贪心算法

455.分发饼干

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

解答:

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

解答:

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. 最大子序和

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

解答:

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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值