贪心
# 860. 柠檬水找零 - 力扣(LeetCode) (opens new window)
class Solution {
public boolean lemonadeChange(int[] bills) {
int crash_5 = 0;
int crash_10 = 0;
for(int i = 0; i < bills.length; i++){
if (bills[i] == 5){
crash_5++;
} else if (bills[i] == 10){
crash_5--;
crash_10++;
} else if (bills[i] == 20){
if(crash_10 > 0){
crash_10--;
crash_5--;
} else {
crash_5 -= 3;
}
}
if (crash_5 < 0 || crash_10 < 0) return false;
}
return true;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 56. 合并区间 - 力扣(LeetCode) (opens new window)
class Solution {
public int[][] merge(int[][] intervals) {
if (intervals.length == 0) return new int[0][2];
Arrays.sort(intervals, (a, b) -> a[0] - b[0]);
List<int[]> merged = new ArrayList<>();
merged.add(intervals[0]);
for (int i = 1; i < intervals.length; i++) {
int[] last = merged.get(merged.size() - 1);
if (intervals[i][0] > last[1]) {
merged.add(intervals[i]);
} else {
last[1] = Math.max(intervals[i][1], last[1]);
}
}
return merged.toArray(new int[merged.size()][]);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 179. 最大数 - 力扣(LeetCode) (opens new window)
class Solution {
public String largestNumber(int[] nums) {
String[] strs = new String[nums.length];
for (int i = 0; i < nums.length; i++) {
strs[i] = String.valueOf(nums[i]);
}
// a+b 与 b+a 的字典序比较 定义排序规则,是贪心思想的典型应用
Arrays.sort(strs, (a, b) -> (b + a).compareTo(a + b));
// 如 "00" 需转为 "0"
if (strs[0].equals("0")) return "0";
return String.join("", strs);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
编辑 (opens new window)
上次更新: 2025/07/25, 12:08:10