Every day a Leetcode
题目来源:881. 救生艇
解法1:贪心 + 排序 + 双指针
排序后,使用双指针分别指向数组首尾,每次取两个指针指向的元素之和与 limit 比较,如果小于等于 limit,则两个指针同时向中间移动一位,否则只移动右指针。累加答案即可。
代码:
/*
* @lc app=leetcode.cn id=881 lang=cpp
*
* [881] 救生艇
*/
// @lc code=start
class Solution
{
public:
int numRescueBoats(vector<int> &people, int limit)
{
int n = people.size();
ranges::sort(people);
int i = 0, j = n - 1;
int ans = 0;
while (i <= j)
{
if (people[i] + people[j] <= limit)
i++;
j--;
ans++;
}
return ans;
}
};
// @lc code=end
结果:
复杂度分析:
时间复杂度:O(nlogn),其中 n 是数组 nums 的长度。
空间复杂度:O(1)。