思路:sort + 双指针;
疑问:就是问什么可以直接选择最小的放入船里面,而不是找到最大容量的情况;因为,船的个人只有2个人,最大重量已经拿出来了,就算能找到一个最合适的重量,那么其他次大重量也是无法达到最优;如果是没有人员限制的话,就是一个背包问题了
int numRescueBoats(vector<int>& people, int limit) {
sort(people.begin(), people.end());
int left = 0;
int right = people.size() - 1;
int ans = 0;
while (right >= 0 && people[right] == limit) {
ans += 1;
right -= 1;
}
while(left < right) {
int sum = people[left] + people[right];
if (sum <= limit) {
ans += 1;
left += 1, right -= 1;
} else {
ans += 1;
right -= 1;
}
}
if (left == right) {
ans += 1;
}
return ans;
}
上述代码可进行优化,优化后
int numRescueBoats(vector<int>& people, int limit) {
sort(people.begin(), people.end());
int left = 0;
int right = people.size() - 1;
int ans = 0;
while(left <= right) {
int sum = people[left] + people[right];
/合并left == right情况
if (sum <= limit) {
ans += 1;
left += 1, right -= 1;
//合并people[right]==limit情况
} else {
ans += 1;
right -= 1;
}
}
return ans;
}