forked from larissalages/code_problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1387.cpp
More file actions
64 lines (53 loc) · 1.37 KB
/
1387.cpp
File metadata and controls
64 lines (53 loc) · 1.37 KB
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
//method1:
class Solution {
public:
int get(int val, vector<int>& dp)
{
if (val < dp.size() && dp[val] != INT_MAX)
return dp[val];
auto next = val % 2 ? 3 * val + 1 : val / 2;
auto result = get(next, dp) + 1;
if (val < dp.size())
dp[val] = result;
return result;
}
int getKth(int lo, int hi, int k)
{
vector<int> dp(hi * 3 + 2, INT_MAX);
dp[1] = 0;
vector<pair<int, int>> vals;
for (int i = lo; i <= hi; ++i)
vals.push_back({get(i, dp), i});
nth_element(vals.begin(), next(vals.begin(), k - 1), vals.end());
return vals[k - 1].second;
}
};
//method2:
class Solution {
public:
int power(int x,map<int,int> &powers){
if(x==1) return 1;
if(powers.find(x)!=powers.end()) return powers[x];
if(x%2==0){
powers[x]=1+power(x/2,powers);
}else{
powers[x]=1+power(3*x+1,powers);
}
return powers[x];
}
int getKth(int lo, int hi, int k) {
map<int,int> powers;
multimap<int,int> powerArray;
for(int i=lo;i<=hi;i++){
powerArray.insert(pair<int,int> (power(i,powers)-1,i));
}
for(auto &it: powerArray){
k--;
if(!k){
ans=it.second;
break;
}
}
return ans;
}
};