-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathsort-integers-by-the-power-value.cpp
66 lines (59 loc) · 1.54 KB
/
sort-integers-by-the-power-value.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
64
65
66
// Time: O(n) on average
// Space: O(n)
class Solution {
public:
int getKth(int lo, int hi, int k) {
vector<pair<int, int>> arr;
for (int i = lo; i <= hi; ++i) {
arr.emplace_back(power_value(i), i);
}
auto it = begin(arr) + k - 1;
nth_element(begin(arr), it, end(arr));
return it->second;
}
private:
int power_value(int x) {
int y = x, result = 0;
while (x > 1 && !Solution::dp_.count(x)) {
++result;
if (x & 1) {
x = 3 * x + 1;
} else {
x >>= 1;
}
}
Solution::dp_[y] = result + Solution::dp_[x];
return Solution::dp_[y];
}
static unordered_map<int, int> dp_;
};
unordered_map<int, int> Solution::dp_;
// Time: O(nlogn)
// Space: O(n)
class Solution2 {
public:
int getKth(int lo, int hi, int k) {
vector<pair<int, int>> arr;
for (int i = lo; i <= hi; ++i) {
arr.emplace_back(power_value(i), i);
}
sort(begin(arr), end(arr));
return arr[k - 1].second;
}
private:
int power_value(int x) {
int y = x, result = 0;
while (x > 1 && !Solution2::dp_.count(x)) {
++result;
if (x & 1) {
x = 3 * x + 1;
} else {
x >>= 1;
}
}
Solution2::dp_[y] = result + Solution2::dp_[x];
return Solution2::dp_[y];
}
static unordered_map<int, int> dp_;
};
unordered_map<int, int> Solution2::dp_;