1. 柠檬水找零
简化为 5元 和 10元两种
class Solution {
public boolean lemonadeChange(int[] bills) {
int five = 0;
int ten = 0;
for(int i = 0; i < bills.length; i++){
if(bills[i] == 5){
five++;
}else if(bills[i] == 10){
ten++;
five--;
}else if(bills[i] == 20){ //15
if(ten > 0){ //-5-10
ten--;
five--;
}else{ // -5-5-5
five -= 3;
}
}
if(five < 0 || ten < 0)
return false;
}
return true;
}
}
2. 根据身高重建队列
先按照身高降序排序,身高相等的,再按k升序排序
最后按照 k 值插入到队列中
class Solution {
public int[][] reconstructQueue(int[][] people) {
Arrays.sort(people, (o1, o2) ->{
if(o1 == o2)
return o1[1] - o2[1];
return o2[0] - o1[0];
});
LinkedList<int[]> queue = new LinkedList<>();
for(int[] i: people){
queue.add(i[1], i);
}
return queue.toArray(new int[people.length][]);
}
}
[hi, ki]
表示第i
个人的身高为hi
,前面 正好 有ki
个身高大于或等于hi
的人。
3. 用最少数量的箭引爆气球
452. 用最少数量的箭引爆气球 - 力扣(LeetCode)
按照左边界从小到大排序,比较相邻的区间是否有重叠
没有重叠,需要一只箭射爆前一个气球
有重叠,则将当前区间的右边界更新为两个区间的公共部分右边界的最小值(相当于把两个区间融合成一个了),用来判断是否和下一个区间有重叠
class Solution {
public int findMinArrowShots(int[][] points) {
Arrays.sort(points, (a, b) -> Integer.compare(a[0], b[0]));
int res = 1;
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;
}
}