881. 救生艇

救生艇

解法一: 完全贪心

java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public int numRescueBoats(int[] people, int limit) {
Arrays.sort(people);
int n = people.length;
PriorityQueue<Integer> priorityQueue = new PriorityQueue<>((num1, num2) -> num2 - num1);
int ans = 0;
for (int i = n - 1; i >= 0; i--) {
if (!priorityQueue.isEmpty() && people[i] <= priorityQueue.peek()) {
priorityQueue.poll();
} else {
ans++;
priorityQueue.offer(limit - people[i]);
}
}
return ans;
}
}

解法二: 贪心

go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
func numRescueBoats(people []int, limit int) int {
sort.Ints(people)
n := len(people)
left := 0
right := n - 1
ans := 0
for left <= right {
if people[left]+people[right] <= limit {
left++
}
right--
ans++
}
return ans
}
作者

wuhunyu

发布于

2024-06-10

更新于

2025-01-15

许可协议