forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
51 lines (40 loc) · 1.07 KB
/
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/// Source : https://leetcode.com/problems/boats-to-save-people/description/
/// Author : liuyubobobo
/// Time : 2018-08-04
#include <iostream>
#include <vector>
using namespace std;
/// Greedy
/// Time Complexity: O(nlogn)
/// Space Complexity: O(1)
class Solution {
public:
int numRescueBoats(vector<int>& people, int limit) {
sort(people.begin(), people.end());
int i = 0, j = people.size() - 1;
int res = 0;
while(i <= j){
if(i == j){
res ++;
break;
}
res ++;
if(people[i] + people[j] <= limit){
i ++;
j --;
}
else
j --;
}
return res;
}
};
int main() {
vector<int> people1 = {1, 2};
cout << Solution().numRescueBoats(people1, 3) << endl; // 1
vector<int> people2 = {3, 2, 2, 1};
cout << Solution().numRescueBoats(people2, 3) << endl; // 3
vector<int> people3 = {3, 5, 3, 4};
cout << Solution().numRescueBoats(people3, 5) << endl; // 4
return 0;
}