-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy path670. Maximum Swap.cpp
42 lines (41 loc) · 1.04 KB
/
670. Maximum Swap.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
// Solution 1.
// Time: O(n^2)
class Solution {
public:
int maximumSwap(int num) {
string s = to_string(num);
for(int i = 0; i < s.size(); i++){
int digit = s[i] - '0';
int index = i;
for(int j = s.size() - 1; j > i; j--){
if(s[j] - '0' > digit){
digit = s[j] - '0';
index = j;
}
}
if(digit != s[i] - '0'){
swap(s[i], s[index]);
return stoi(s);
}
}
return num;
}
};
// Solution 2.
// Time: O(n)
class Solution {
public:
int maximumSwap(int num) {
string s = to_string(num);
vector<int>bucket(10);
for(int i = 0; i < s.size(); i++)
bucket[s[i] - '0'] = i;
for(int i = 0; i < s.size(); i++)
for(int j = 9; j > s[i] - '0'; j--)
if(bucket[j] > i){
swap(s[i], s[bucket[j]]);
return stoi(s);
}
return num;
}
};