(基于java) 算法笔记 —— 贪心算法

贪心算法的学习,简单笔记

1、算法解释

贪心算法/贪心思想:

  • 将全局大问题,分解成若干局部小问题
  • 使局部小问题为最优
  • 全局大问题成为最优

2、分配问题

① LeetCode 455 分发饼干

解题思想——贪心思想

  • 对于【孩子】、【饼干】数组,先进行排序
  • 从左往右,用饼干【满足】孩子
    • 如果满足,当前的孩子和饼干就“移出”
    • 如果不满足,当前饼干“移出”,让后面的饼干来
  • 返回输出满足孩子的总数量

Java解答——贪心解法

class Solution {
   
    public int findContentChildren(int[] g, int[] s) {
   
        Arrays.sort(g);
        Arrays.sort(s);
        int child = 0, cookie = 0;
        while(child < g.length && cookie < s.length){
   
            if(g[child] <= s[cookie]){
    // 孩子能吃饱
                child++;    // 孩子后移
            } 
            cookie++;   // 饼干后移
        }
        return child;
    }
}

② LeetCode 135 分发糖果

解题思想——贪心思想

  • 创建两个临时数组,用于存放分数高而多获得的糖果
  • 从左往右、从右往左,两次遍历,相邻的比较,更新糖果数量
  • 最后将两个临时数组中,每个孩子获得最多的糖果数加和
  • 如:
    • // Input [1 2 3 2 1]
    • // candy_left [0 1 2 0 0]
    • // candy_right [0 0 2 1 0]
    • // sum = len + 0 + 1 + 2 + 1 + 0 = 9

Java解答——贪心解法

class Solution {
   
    public int candy(int[] ratings) {
   
        int len = ratings.length;
        int sum_candy = len;	// 每位孩子至少得一颗糖果
        int[] candy_left = new int[len];
        int[] candy_right = new int[len];

        for(int i = 0; i < len - 1; i++){
   	// for循环,确定两个临时数组的值
            if(ratings[i] < ratings[i+1]){
     // 右边分数比左边大
                candy_left[i+1] = candy_left[i] + 1;  // 右边糖果比左边的多1
            }
            if(ratings[len-1-i]<ratings[len-2-i]){
     // 左边分数比右边大
                candy_right[len-2-i] = candy_right[len-1-i] + 1;
            }
        }
        for(int i = 0; i < len; i++){
   	// for循环,用于计算糖果总和
            sum_candy+= Math.max(candy_left[i], candy_right[i]);
        }
        return sum_candy;
    }
}

3、区间问题

① LeetCode 435 无重叠区间

解题思想——贪心思想

  • 首先将各个区间,根据右边界的大小重新排序
  • 如果下个区间的左边界比当前区间的右边界大,说明无重叠
  • 关键在于对各区间的排序,即对二维数组的排序
    Java中的二维数组排序
/*
注意compare 排序中默认升序:
     返回 1 == true 代表降序,我想调整顺序
     返回 -1 代表升序
*/

 Arrays.sort(arrays, new Comparator<int[]>() {
   
     
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值