-
Notifications
You must be signed in to change notification settings - Fork 64
/
Copy pathBoatstoSavePeople.java
105 lines (70 loc) · 2.03 KB
/
BoatstoSavePeople.java
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/*
Source: https://leetcode.com/problems/boats-to-save-people/submissions/
Approach 1(Extended version of Approach 2 for easy understanding)
Basic Idea:
Try to make larger weight people sit first and if some space left afterwards, then check whether smaller weight person can fit in same boat
Time: O(n logn), where n is the size of the given array(people)
Space: O(1), in-place
*/
class Solution {
public int numRescueBoats(int[] people, int limit) {
Arrays.sort(people);
int start = 0;
int end = people.length - 1;
int boats = 0;
while(start <= end) {
if(people[end] == limit) {
--end;
} else if(people[start] + people[end] <= limit) {
++start;
--end;
} else { // for cases like [6, 7, 8] and limit = 13, make the person sit having weight 8 (because 6 + 8 > 13)
--end;
}
++boats;
}
return boats;
}
}
----------------------------------------------------------------------------------------------------
/*
Approach 2(More optimised)
Time: O(n logn), where n is the size of the given array(people)
Space: O(1), in-place
*/
class Solution {
public int numRescueBoats(int[] people, int limit) {
Arrays.sort(people);
int boats = 0;
int start = 0;
int end = people.length - 1;
while(start <= end) {
if(people[start] + people[end] <= limit) {
++start;
}
--end;
++boats;
}
return boats;
}
}
----------------------------------------------------------------------------------------------------
/*
Approach 3(More optimised without using extra variable boats and thus eliminating ++boats operation)
Time: O(n logn), where n is the size of the given array(people)
Space: O(1), in-place
*/
class Solution {
public int numRescueBoats(int[] people, int limit) {
Arrays.sort(people);
int start = 0;
int end = people.length - 1;
while(start <= end) {
if(people[start] + people[end] <= limit) {
++start;
}
--end;
}
return people.length - 1 - end;
}
}