第八章 贪心算法 part04
大纲
● 860.柠檬水找零
● 406.根据身高重建队列
● 452. 用最少数量的箭引爆气球
leetcode 860
柠檬水找零
class Solution {
public boolean lemonadeChange(int[] bills) {
int five = 0, ten = 0;
for (int bill : bills) {
if (bill == 5) five++;
else if (bill == 10) {
if (five < 1) return false;
five--;
ten++;
}
else {
if (ten > 0 && five > 0) {
ten--;
five--;
} else if (five > 2) five -= 3;
else return false;
}
}
return true;
}
}
leetcode 406
根据身高重建队列
class Solution {
public int[][] reconstructQueue(int[][] people) {
Arrays.sort(people, (a, b) -> {
if (a[0] == b[0]) return a[1] - b[1];
return b[0] - a[0];
});
LinkedList<int[]> queue = new LinkedList<>();
for (int[] p : people) queue.add(p[1], p);
return queue.toArray(new int[queue.size()][]);
}
}
leetcode 452
用最少数量的箭引爆气球
class Solution {
public int findMinArrowShots(int[][] points) {
int res = 1;
Arrays.sort(points, (a, b) -> Integer.compare(a[0], b[0]));
for (int i = 1; i < points.length; i++) {
if (points[i][0] > points[i - 1][1]) res++;
else points[i][1] = Math.min(points[i][1], points[i - 1][1]);
}
return res;
}
}