代码随想录第三十五天 | 贪心算法

 第三十五天,继续贪心
 

860.柠檬水找零 

class Solution {
    public boolean lemonadeChange(int[] bills) {
        int n = bills.length;
        if(bills[0] > 5){
            return false;
        }
        int five = 0;
        int ten = 0;
        int twenty = 0;
        for(int i = 0; i<n; i++){
            if(bills[i] == 5){
                five += 1;
            }
            else if(bills[i] == 10){
                if(five>0){
                    five --;
                    ten ++;
                }
                else{
                    return false;
                }

            }
            else{
                if(ten > 0 && five >0){
                    five --;
                    ten --;
                }
                else if(five > 2){
                    five -= 3;
                }
                else{
                    return false;
                }
            }
        }
        return true;
    }
}

有5就加上;有10就看有没有5,再加上10;有20就看有没有足够的5和10,不用管20;

406.根据身高重建队列 

class Solution {
    public int[][] reconstructQueue(int[][] people) {
        int n = people.length;
        LinkedList<int[]> queue = new LinkedList<>();
        Arrays.sort(people, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                if (o1[0]==o2[0]) {
                    return o1[1]-o2[1];
                }
                return o2[0] - o1[0];
            }
        }); 

        queue.add(people[0]);
        for(int i = 1; i<n; i++){
            queue.add(people[i][1],people[i]);
        }
        

        return queue.toArray(new int[n][]);

    }
}

先由高到低排序好,如果是一样的身高,那就根据数组的第二个格子由低到高排列,排列后再依次插队到res里

452. 用最少数量的箭引爆气球 

 

class Solution {
    public int findMinArrowShots(int[][] points) {
        int n = points.length;
        Arrays.sort(points, (a, b) -> Integer.compare(a[0], b[0]));
        int res = 1;
        for(int i = 1; i<n; i++){
            if(Integer.compare(points[i][0], points[i-1][1])>0){
                res ++;
            }
            else{
                points[i][1] = Math.min(points[i][1], points[i-1][1]);
            }
        }
        return res;
    }
}

这道题就看当前的气球和另一个气球是否有重合,如果有的话,就缩短两个气球的最大边界值为同样短,这样就可以判断当前之后的气球是否可以连当前之前的一起射穿,没有的话就再射出一根箭。

posted @ 2022-11-16 13:34  小猫Soda  阅读(29)  评论(0)    收藏  举报