LeetCode:
1.思路
直接创建5-10两个变量,遍历结束后看两个变量数是否小于0,如果小于则说明不满足顺序实现找零。
2.代码实现
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) {
five--;
ten++;
} else if (bills[i] == 20) {
if (ten > 0) {
ten--;
five--;
} else {
five -= 3;
}
}
if (five < 0 || ten < 0) {
return false;
}
}
return true;
}
}
// 练习以下map
class Solution {
public boolean lemonadeChange(int[] bills) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < bills.length; i++) {
if (bills[i] == 5) {
map.put(5, map.getOrDefault(5, 0) + 1);
} else if (bills[i] == 10) {
if (map.getOrDefault(5, 0) < 1) {
return false;
}
map.put(10, map.getOrDefault(10, 0) + 1);
map.put(5, map.get(5) - 1);
} else if (bills[i] == 20) {
if (map.getOrDefault(5, 0) < 1 || map.getOrDefault(10, 0) < 1) {
if (map.getOrDefault(5, 0) < 3) {
return false;
}
map.put(5, map.get(5) - 3); // 覆盖作用??
} else {
map.put(5, map.get(5) - 1);
map.put(10, map.get(10) - 1);
}
}
}
return true;
}
}
3.复杂度分析
时间复杂度:O(n).
空间复杂度:O(1).
LeetCode:406. 根据身高重建队列 - 力扣(LeetCode)
1.思路
根据身高进行排序,如果身高相同则按照位置大小升序排序。创建一个链表辅助构建结果集,遍历数组通过k作为索引加入到链表中,将链表转化为数组返回即可。
2.代码实现
class Solution {
public int[][] reconstructQueue(int[][] people) {
// 按照身高降序排序,如果身高相同则按照k值升序排序
Arrays.sort(people, (a, b) -> {
if (a[0] == b[0]) {
return a[1] - b[1];
}
return b[0] - a[0];
});
// 使用链表作为辅助数据结构
LinkedList<int[] que> que = new LinkedList<>();
// 遍历排序后的数组
for (int[] p : people) {
// 在p[1]的位置插入p元素
que.add(p[1], p);
}
// 将链表转换为二维数组并返回结果
return que.toArray(new int[people.length][]);
}
}
3.复杂度分析
时间复杂度:O(n).
空间复杂度:O(n).
LeetCode:452. 用最少数量的箭引爆气球 - 力扣(LeetCode)
1.思路
画图查覆盖性,按照左边界排序,当右一左边界大于左一右边界,说明没有交集,需要增加一支箭,当左一右侧大于右一左侧说明两者有交叉,更新当前i线段的右边界为公共右边界(两者之间的较小值)。
2.代码实现
class Solution {
public int findMinArrowShots(int[][] points) {
// 排序
Arrays.sort(points, (a, b) -> Integer.compare(a[0], b[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][1], points[i][1]);
}
}
return count;
}
}
3.复杂度分析
时间复杂度:O(nlogn).
空间复杂度:O(1).