forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
house-robber-iv.cpp
63 lines (60 loc) · 1.7 KB
/
house-robber-iv.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
52
53
54
55
56
57
58
59
60
61
62
63
// Time: O(nlogn)
// Space: O(n)
// binary search, greedy
class Solution {
public:
int minCapability(vector<int>& nums, int k) {
const auto& check = [&](const auto& x) {
int cnt = 0;
for (int i = 0; i < size(nums); ++i) {
if (nums[i] <= x) {
++cnt;
++i;
}
}
return cnt >= k;
};
unordered_set<int> nums_set(cbegin(nums), cend(nums));
vector<int> sorted_nums(cbegin(nums_set), cend(nums_set));
sort(begin(sorted_nums), end(sorted_nums));
int left = 0, right = size(sorted_nums) - 1;
while (left <= right) {
const auto mid = left + (right - left) / 2;
if (check(sorted_nums[mid])) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return sorted_nums[left];
}
};
// Time: O(nlogr)
// Space: O(1)
// binary search, greedy
class Solution2 {
public:
int minCapability(vector<int>& nums, int k) {
const auto& check = [&](const auto& x) {
int cnt = 0;
for (int i = 0; i < size(nums); ++i) {
if (nums[i] <= x) {
++cnt;
++i;
}
}
return cnt >= k;
};
int left = *min_element(cbegin(nums), cend(nums));
int right = *max_element(cbegin(nums), cend(nums));
while (left <= right) {
const auto mid = left + (right - left) / 2;
if (check(mid)) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return left;
}
};