-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy path_881.java
84 lines (80 loc) · 2.98 KB
/
_881.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
package com.fishercoder.solutions;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;
public class _881 {
public static class Solution1 {
public int numRescueBoats(int[] people, int limit) {
TreeMap<Integer, Integer> map = new TreeMap<>();
for (int w : people) {
map.put(w, map.getOrDefault(w, 0) + 1);
}
int boats = 0;
List<Integer> uniqWeights = new ArrayList(map.keySet());
int left = 0;
int right = uniqWeights.size() - 1;
while (left < right) {
int heavierWeight = uniqWeights.get(right);
int lighterWeight = uniqWeights.get(left);
if (heavierWeight + lighterWeight <= limit) {
int pairs = Math.min(map.get(heavierWeight), map.get(lighterWeight));
boats += pairs;
if (map.get(heavierWeight) == pairs && map.get(lighterWeight) == pairs) {
map.remove(heavierWeight);
map.remove(lighterWeight);
left++;
right--;
} else if (map.get(heavierWeight) == pairs) {
map.remove(heavierWeight);
map.put(lighterWeight, map.get(lighterWeight) - pairs);
right--;
} else {
map.remove(lighterWeight);
map.put(heavierWeight, map.get(heavierWeight) - pairs);
left++;
}
} else {
boats += map.get(heavierWeight);
map.remove(heavierWeight);
right--;
}
}
if (!map.isEmpty()) {
int weight = uniqWeights.get(left);
int remainingPeople = map.get(weight);
if (remainingPeople == 1) {
boats++;
} else {
if (weight * 2 <= limit) {
boats += (remainingPeople / 2 + ((remainingPeople % 2 == 0) ? 0 : 1));
} else {
boats += remainingPeople;
}
}
}
return boats;
}
}
public static class Solution2 {
public int numRescueBoats(int[] people, int limit) {
Arrays.sort(people);
int end = people.length - 1;
int start = 0;
int boatcount = 0;
while (end >= start) {
if (people[end] == limit) {
end--;
boatcount++;
} else if (people[end] + people[start] <= limit) {
start++;
end--;
boatcount++;
} else {
end--;
boatcount++;
}
}
return boatcount;
}
}
}