LeetCode:860.柠檬水找零
1.思路
通过map做映射,记录5,10出现的次数,然后罗列5、10、20出现时对map中元素数量的影响,排除所有不符合条件的,最后符合条件的返回true.
2.代码实现
1class Solution {
2 public boolean lemonadeChange(int[] bills) {
3 // 映射
4 Map<Integer, Integer> map = new HashMap<>();
5 map.put(5, 0);
6 map.put(10, 0);
7 for (int i = 0; i < bills.length; i++) {
8 if (bills[i] == 5) {
9 map.put(5, map.get(5) + 1);
10 } else if (bills[i] == 10) {
11 if (map.get(5) > 0) {
12 map.put(5, map.get(5) - 1);
13 map.put(10, map.get(10) + 1);
14 } else {
15 return false;
16 }
17 } else if (bills[i] == 20){
18 if (map.get(5) > 0 && map.get(10) > 0) {
19 map.put(5, map.get(5) - 1);
20 map.put(10, map.get(10) - 1);
21 } else if (map.get(5) >= 3){
22 map.put(5, map.get(5) - 3);
23 } else {
24 return false;
25 }
26 }
27 }
28 return true;
29 }
30}
3.复杂度分析
时间复杂度:O(n).
空间复杂度:O(1).
LeetCode:406.根据身高重建队列
1.思路
先判断身高,从高到低排列,对于相同身高按照k值从低到高排列。
方法不熟悉,调用还挺难的…
2.代码实现
1class Solution {
2 public int[][] reconstructQueue(int[][] people) {
3 Arrays.sort(people, (a, b) -> a[0] == b[0] ? a[1] - b[1] : b[0] - a[0]);
4
5 List<int[]> list = new ArrayList<>();
6
7 for (int i = 0; i < people.length; i++) {
8 int[] person = people[i];
9 list.add(person[1], person);
10 }
11 return list.toArray(new int[people.length][]);
12 }
13}
3.复杂度分析
时间复杂度:O(n^2).
空间复杂度:O(n).
LeetCode:452. 用最少数量的箭引爆气球
452. 用最少数量的箭引爆气球 - 力扣(LeetCode)
1.思路
对齐左边界,更新右边界,思路清晰,方法调用较弱
2.代码实现
1class Solution {
2 public int findMinArrowShots(int[][] points) {
3 Arrays.sort(points, (a, b) -> Integer.compare(a[0] , b[0]));
4
5 int count = 1;
6 for (int i = 1; i < points.length; i++) {
7 if (points[i][0] > points[i - 1][1]) {
8 count++;
9 } else {
10 points[i][1] = Math.min(points[i - 1][1], points[i][1]);
11 }
12 }
13 return count;
14 }
15}
3.复杂度分析
时间复杂度:O(logn).
空间复杂度:O(1).
4.视频解析