LeetCode 860柠檬水找零
简单模拟题,分情况讨论,用两个变量维护即可
class Solution {
public boolean lemonadeChange(int[] bills) {
int num5 = 0;
int num10 = 0;
for (int i = 0; i < bills.length; i++) {
if (bills[i] == 5) num5++;
if (bills[i] == 10) {
if (num5 > 0) {
num5--; num10++;
} else return false;
}
if (bills[i] == 20) {
if (num10 > 0 && num5 > 0) {
num10--; num5--;
} else if (num5 >= 3) {
num5 -= 3;
} else return false;
}
}
return true;
}
}
LeetCode 406 根据身高重建队列
这题其实非常巧妙,数组中位置i处的人身高是people[i][0],规定在这个人前面身高比他高的有people[1]人。乍一看非常懵,但仔细找规律后发现,按照身高倒序同时people[1]较小在前的方式排列后,其实将原数组中元素按照people[1]的下标直接插入就可满足要求。这时在他前面绝对有people[1]个比他高的人,由于题目规定绝对符合规则,同等身高的人只要按people[1]较小在前的方式排列,也绝对不会出错。
代码如下:
class Solution {
public int[][] reconstructQueue(int[][] people) {
Arrays.sort(people, (a,b)->{
if (a[0] == b[0]) return a[1] - b[1];
else return b[0] - a[0];
});
LinkedList<int[]> que = new LinkedList<>();
for (int[] p : people) {
que.add(p[1],p);
}
return que.toArray(new int[people.length][]);
}
}
LeetCode 452 用最少数量的箭引爆气球🗡
主要是要先排序,将气球们按照起始位置先后进行排序。之后要用到双指针,但是要注意维护重叠气球之间最小右边界,注意是最小右边界,否则之前重叠的节点会漏计数,等遇到一个不相邻的气球时,就可以进行计数并移动下标了。
代码如下:
class Solution {
public int findMinArrowShots(int[][] points) {
Arrays.sort(points, (a,b)->Integer.compare(a[0], b[0]));
int num = 1;
int j = 0;
for (int i = 0; i < points.length; i++) {
while (j < points.length && points[j][0] <= points[i][1]) {
points[i][1] = Math.min(points[i][1], points[j][1]);
j++;
}
if (j < points.length) {
num++;
i = j - 1;
}
else break;
}
return num;
}
}