算法修炼Day35|● 860.柠檬水找零 ● 406.根据身高重建队列 ● 452. 用最少数量的箭引爆气球

50 阅读1分钟
题目:860. 柠檬水找零 - 力扣(LeetCode)
代码实现:
class Solution {
    public boolean lemonadeChange(int[] bills) {
        Map<Integer, Integer> map = new HashMap<>();
        map.put(5, 0); // 很关键,不加入会报空指针异常
        map.put(10, 0);
        for (int i = 0; i < bills.length; i++) {
            if (bills[i] == 5) {
                map.put(5, map.getOrDefault(5, 0) + 1);
            } else if (bills[i] == 10) {
                if (map.get(5) > 0) {
                    map.put(10, map.getOrDefault(10, 0) + 1);
                    map.put(5, map.get(5) - 1);
                } else {
                    return false;
                }
            } else {
                if (map.get(10) > 0 && map.get(5) > 0) {
                    map.put(10, map.get(10) - 1);
                    map.put(5, map.get(5) - 1);
                } else if (map.get(5) > 2) {
                    map.put(5, map.get(5) - 3);
                } else {
                    return false;
                }
            }
        }
        return true;
    }
}

class Solution {
    public boolean lemonadeChange(int[] bills) {
        int five = 0;
        int ten = 0;
        for (int bill : bills) {
            if (bill == 5) {
                five++;
            } else if (bill == 10) {
                if (five > 0) {
                    five--;
                    ten++;
                } else {
                    return false;
                }
            } else {
                if (ten > 0 && five > 0) {
                    ten--;
                    five--;
                } else if (five > 2) {
                    five -= 3;
                } else {
                    return false;
                }
            }
        }
        return true;
    }
}
题目:406. 根据身高重建队列 - 力扣(LeetCode)
代码实现:
class Solution {
    public int[][] reconstructQueue(int[][] people) {
        // 高个子先排,矮个子后排,相同高度的按照k值进行排序
        Arrays.sort(people, (o1, o2) -> o1[0] == o2[0] ? o1[1] - o2[1] : o2[0] - o1[0]);
        // 将排好序的结果调整到指定位置
        List<int[]> ans = new ArrayList<>();
        for (int i = 0; i < people.length; i++) { // people[i][1] 获取的就是指定位置
            ans.add(people[i][1], people[i]);
        }
        // 三种方式都能正确输出
        return ans.toArray(people);
        // return ans.toArray(new int[people.length][]);
        // return ans.toArray(new int[people.length][2]);
    }
}
题目:452. 用最少数量的箭引爆气球 - 力扣(LeetCode)
代码实现:
class Solution {
    public int findMinArrowShots(int[][] points) {
        // 排序
        Arrays.sort(points, (o1, o2) -> Integer.compare(o1[0], o2[0]));
        int count = 1;
        for (int i = 1; i < points.length; i++) {
            if (points[i][0] <= points[i - 1][1]) {
                points[i][0] = Math.max(points[i][0], points[i - 1][0]);
                points[i][1] = Math.min(points[i][1], points[i - 1][1]);
            } else {
                count++;
            }
        }
        return count;
    }
}