做这一题的时候我用了贪心,但是没有用双指针,所以超时了
超时代码
class Solution {
public:
int numRescueBoats(vector<int>& people, int limit) {
sort(people.begin(), people.end());
reverse(people.begin(), people.end());
int n = people.size();
vector<int> vis(n);
int l = 0;
int cnt = 0;
int ans = 0;
for (int i = 0; i < n; i++) {
if (cnt == n) {
break;
}
for (int j = l; j < n; j++) {
if (!vis[j]) {
l = j; vis[l] = 1;
break;
}
}
cnt++;
for (int k = l + 1; k < n; k++) {
if (people[l] + people[k] <= limit && vis[k]==0) {
cnt++; vis[k] = 1; break;
}
}
ans++;
}
return ans;
}
};
但是要用双指针
class Solution {
public:
int numRescueBoats(vector<int> &people, int limit) {
int ans = 0;
sort(people.begin(), people.end());
int light = 0, heavy = people.size() - 1;
while (light <= heavy) {
if (people[light] + people[heavy] > limit) {
--heavy;
} else {
++light;
--heavy;
}
++ans;
}
return ans;
}
};
为什么可以用双指针呢,这个问题交给你了