860.柠檬水找零
- 刷题https://leetcode.cn/problems/lemonade-change/description/
- 文章讲解https://programmercarl.com/0860.%E6%9F%A0%E6%AA%AC%E6%B0%B4%E6%89%BE%E9%9B%B6.html
- 视频讲解https://www.bilibili.com/video/BV12x4y1j7DD/?vd_source=af4853e80f89e28094a5fe1e220d9062
-
题解:
class Solution {
public boolean lemonadeChange(int[] bills) {
//因为找零不会用到20的,所以这里并不对20的进行统计
int five = 0;
int ten = 0;
for(int i = 0; i < bills.length; i++){
if(bills[i] == 5){
//当客户给了5时,不需找零,直接计入
five++;
}else if(bills[i] == 10){
//当客户给了10时,只有一种方案,找5收10
//若无5,则false
five--;
ten++;
}else if(bills[i] == 20){
//当客户给了20,方案有两种
//1、收20找10+5。2、收20找5+5+5
//因为5的实用找零方案更多,所以这里需要优先消耗10
//贪心也体现在了优先消耗10中
if(ten > 0){
//若还有10
ten--;
five--;
}else{
//若没有10,只能5+5+5
five-=3;
}
}
//当5或者10减为负数,则说明5或者10不够消耗,则不能成功弯沉找零
if(five < 0 || ten < 0){
return false;
}
}
//当循环完成之后5或者10仍为正(未消耗为负),则可以成功找零
return true;
}
}
406.根据身高重建队列
- 刷题https://leetcode.cn/problems/queue-reconstruction-by-height/description/
- 文章讲解https://programmercarl.com/0406.%E6%A0%B9%E6%8D%AE%E8%BA%AB%E9%AB%98%E9%87%8D%E5%BB%BA%E9%98%9F%E5%88%97.html
- 视频讲解https://www.bilibili.com/video/BV1EA411675Y/?vd_source=af4853e80f89e28094a5fe1e220d9062
-
题解:
class Solution {
//本题有两个维度,不能两边一起贪,会顾此失彼
public int[][] reconstructQueue(int[][] people) {
//先对身高从大到小排序,同样身高下排序号小的在前面
Arrays.sort(people, new Comparator<int[]>(){
//定义比较器,排序规则是根据一个自定义的比较器Comparator<int[]>进行比较。
//在比较器中,定义了compare方法,比较两个int数组person1和person2。
//首先比较两个数组的第一个元素,如果不相等,则返回它们的差值;如果相等,
//则比较它们的第二个元素,返回它们的差值。最终根据比较结果对people数组进行排序。
public int compare(int[] person1, int[]person2){
if(person1[0] != person2[0]){
return person2[0] - person1[0];
}else{
return person1[1] - person2[1];
}
}
});
List<int[]> result = new ArrayList<int[]>();
for(int[] person : people){
result.add(person[1], person);
}
return result.toArray(new int[result.size()][]);
}
}
452. 用最少数量的箭引爆气球
- 刷题https://leetcode.cn/problems/minimum-number-of-arrows-to-burst-balloons/description/
- 文章讲解https://programmercarl.com/0452.%E7%94%A8%E6%9C%80%E5%B0%91%E6%95%B0%E9%87%8F%E7%9A%84%E7%AE%AD%E5%BC%95%E7%88%86%E6%B0%94%E7%90%83.html
- 视频讲解https://www.bilibili.com/video/BV1SA41167xe/?vd_source=af4853e80f89e28094a5fe1e220d9062
-
题解:
class Solution {
public int findMinArrowShots(int[][] points) {
if(points.length == 0){
return 0;
}
//先根据气球直径开始坐标(第一个数)从小到大排序,
//ps:Integer内置比较方法不会溢出
Arrays.sort(points, (a, b) -> Integer.compare(a[0], b[0]));
//当长度不为0,至少要用一支箭
int count = 1;
for(int i = 1; i < points.length; i++){
//当前的左坐标大于上一个的右坐标,则这两个无重叠,需要两支箭
if(points[i][0] > points[i - 1][1]){
count++;
}else{
//有重叠,则更新上一个的右坐标的变量
//选取这一个和上一个的右坐标的最小值,作为下一次迭代的右坐标
points[i][1] = Math.min(points[i][1], points[i - 1][1]);
}
}
return count;
}
}