881. Boats to Save People - Medium
前往題目
想法
- 雙指針,因為最多兩人,所以蠻簡單的
思路
- 排序,由小到大
- 雙指針,最左和最右,一開始都先取當前可能的最大值
- 然後再判斷能否再取一個當前最小值
- 移動指針
Code
class Solution {
public int numRescueBoats(int[] people, int limit) {
Arrays.sort(people);
int l = 0, r = people.length - 1;
int res = 0;
while (l <= r) {
int weight = people[r];
// Haven't over weight
if (weight + people[l] <= limit) {
++l;
}
++res;
--r;
}
return res;
}
}
881. Boats to Save People - Medium
https://f88083.github.io/2024/06/26/881-Boats-to-Save-People-Medium/