forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
the-k-strongest-values-in-an-array.cpp
50 lines (47 loc) · 1.37 KB
/
the-k-strongest-values-in-an-array.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
// Time: O(n)
// Space: O(1)
class Solution {
public:
vector<int> getStrongest(vector<int>& arr, int k) {
nth_element(begin(arr), begin(arr) + (arr.size() - 1) / 2, end(arr));
const auto m = arr[(arr.size() -1) / 2];
nth_element(begin(arr), begin(arr) + k, end(arr), [&](int a, int b) {
return abs(a - m) != abs(b - m) ? abs(a - m) > abs(b - m) : a > b;
});
arr.resize(k);
return arr;
}
};
// Time: O(nlogn)
// Space: O(1)
class Solution2 {
public:
vector<int> getStrongest(vector<int>& arr, int k) {
sort(begin(arr), end(arr));
const auto m = arr[(arr.size() -1) / 2];
int left = 0, right = arr.size() - 1;
vector<int> result;
while (result.size() < k) {
if (m - arr[left] > arr[right] - m) {
result.push_back(arr[left++]);
} else {
result.push_back(arr[right--]);
}
}
return result;
}
};
// Time: O(nlogn)
// Space: O(1)
class Solution3 {
public:
vector<int> getStrongest(vector<int>& arr, int k) {
sort(begin(arr), end(arr));
const auto m = arr[(arr.size() -1) / 2];
sort(begin(arr), end(arr), [&](int a, int b) {
return abs(a - m) != abs(b - m) ? abs(a - m) > abs(b - m) : a > b;
});
arr.resize(k);
return arr;
}
};