860 柠檬水找零
https://leetcode.cn/problems/lemonade-change/ 能找大钱时找大钱留小钱。
class Solution {
public boolean lemonadeChange(int[] bills) {
int fiveCount = 0, tenCount = 0;
for (int bill : bills) {
if (bill == 5) {
fiveCount++;
} else if (bill == 10) {
tenCount++;
if (fiveCount == 0) {
return false;
} else {
fiveCount--;
}
} else {
if (fiveCount == 0 || tenCount == 0 && fiveCount < 3) {
return false;
} else if (tenCount != 0) {
tenCount--;
fiveCount--;
} else {
fiveCount -= 3;
}
}
}
return true;
}
}
406 根据身高重建队列
https://leetcode.cn/problems/queue-reconstruction-by-height/
从高到矮,依次插入,插入点的index为比它高的个数,后插入的人因为比它矮就不用管了。注意,当身高相同时,k大的人由于能放高人的范围更大需要排在k小的人的后面。
class Solution {
public int[][] reconstructQueue(int[][] people) {
List<int[]> queue = new LinkedList<>();
Arrays.sort(people, (a, b) -> (Integer.compare(b[0], a[0]) == 0 ? Integer.compare(a[1], b[1]) : Integer.compare(b[0], a[0])));
for (int[] person : people) {
queue.add(person[1], person);
}
int[][] result = new int[people.length][2];
for (int i = 0; i < people.length; i++) {
result[i] = queue.get(i);
}
return result;
}
}
452 用最少数量的箭引爆气球
https://leetcode.cn/problems/minimum-number-of-arrows-to-burst-balloons/
方法一: 按结束时间排序(相同时随意排),在最小结束时间插箭,已经开始的气球忽略不计,直到开始新的不重叠区间继续计数。方法二:按开始时间排序,如果和下一个区间相交,选出相交区间的结束点去更新最后一个区间的结束点;如果不相交,则需新的箭。
class Solution { //1
public int findMinArrowShots(int[][] points) {
Arrays.sort(points, (a, b) -> (Integer.compare(a[1], b[1])));
int count = 1;
int lastEnd = points[0][1];
for (int i = 1; i < points.length; i++) {
if (points[i][0] <= lastEnd) continue;
count++;
lastEnd = points[i][1];
}
return count;
}
}
class Solution { //2
public int findMinArrowShots(int[][] points) {
Arrays.sort(points, (a, b) -> Integer.compare(a[0], b[0]));
int count = 1;
for (int i = 1; i < points.length; i++) {
if (points[i][0] <= points[i - 1][1]) {
points[i][1] = Math.min(points[i][1], points[i - 1][1]);
} else {
count++;
}
}
return count;
}
}