860. Lemonade Change
题目链接:860. Lemonade Change
思路链接:代码随想录贪心算法-柠檬水找零
思路
这道题看起来很难,实际上只要考虑三种情况:
- 给了五块:直接收下(+1)
- 给了十块:需要找5块,看当前有没有5块
- 给了二十块:需要找15块,优先用10块找,因为10块只能用于找给20块的情况;如果没有10块,那么就用5块找
局部最优:遇到账单20,优先消耗美元10,完成本次找零
全局最优:完成所有的账单找零
Code
class Solution {
public boolean lemonadeChange(int[] bills) {
int five = 0;
int ten = 0;
// int twenty = 0; // 可以删,因为没用
for (int i = 0; i < bills.length; i++) {
if (bills[i] == 5) {
five++;
} else if (bills[i] == 10) {
if (five <= 0) return false;
five--;
ten++;
} else if (bills[i] == 20) {
// 遇到20,要找15,优先用已有的10去找钱,因为10只能用来找20的钱
if (ten > 0 && five > 0) {
ten--;
five--;
} else if (ten <= 0 && five >= 3){
five -= 3;
} else {
return false;
}
}
}
return true;
}
}
406. Queue Reconstruction by Height
题目链接:406. Queue Reconstruction by Height
思路链接:代码随想录贪心算法-根据身高重建队列
思路
这里出现了两个维度,策略就是二个维度分开考虑。先将所有元素按照身高从大到小排,然后再按照k来插入,这样后面的元素就不会影响前面的元素。
局部最优:优先通过身高排序,然后插入操作过后的部分队列满足要求
全局最优:做完操作后的整个队列都能满足要求
Code
import java.util.List;
import java.util.LinkedList;
class Solution {
public int[][] reconstructQueue(int[][] people) {
// Arrays.sort(people, new QueueComparator()); // 利用lambda表达式更快
// 以身高从大到小排序
Arrays.sort(people, (a, b) -> {
if (a[0] == b[0]) return a[1] - b[1];
return b[0] - a[0];
});
List<int[]> result = new LinkedList<>();
// 把排序后的数组中的一个一个插入list,按照前方有多少人的身高大于或等于当前人的身高
for (int i = 0; i < people.length; i++) {
result.add(people[i][1], people[i]);
}
// 将list转化成数组
return result.toArray(new int[people.length][]);
}
}
// 构造Comparator
// class QueueComparator implements Comparator<int[]> {
// public int compare(int[] a, int[] b) {
// if (a[0] == b[0]) {
// return a[1] - b[1];
// } else {
// return b[0] - a[0];
// }
// }
// }
452. Minimum Number of Arrows to Burst Balloons
题目链接:452. Minimum Number of Arrows to Burst Balloons
思路链接:代码随想录贪心算法-用最少数量的箭引爆气球
思路
思路是当气球区间有重合时尽可能地一箭射完。为了直观,将所有气球按照左区间大小进行排序,然后确定重合气球的最小右边界(射一次箭),如果遍历过去发现有气球没有重合,那么就要把最小右边界变更为当前没有重合的气球的右边界。
局部最优:每次射箭尽可能多得射气球
全局最优:用最少数量的箭射完所有气球
Code
class Solution {
public int findMinArrowShots(int[][] points) {
if (points.length <= 1) {
return points.length;
}
int result = 1;
// 将数组按照半径的起始位置从小到大排序
Arrays.sort(points, (a, b) -> {
return Integer.compare(a[0], b[0]);
});
// 定义最小右边界
int minLine = points[0][1];
for (int i = 1; i < points.length; i++) { // 从第二个元素开始
// 如果发现当前区间与最小右边界(上一次循环得到的最小右边界)重合,就重新定义最小右边界
if (minLine >= points[i][0]) {
minLine = Math.min(minLine, points[i][1]);
// System.out.println(minLine);
} else { // 如果没有重合,就把最小右边界变更为当前区间的右边界
minLine = points[i][1];
result++;
}
}
return result;
}
}