-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path670.cpp
More file actions
33 lines (32 loc) · 862 Bytes
/
Copy path670.cpp
File metadata and controls
33 lines (32 loc) · 862 Bytes
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
class Solution {
public:
int maximumSwap(int num) {
vector<int> vec, latest(10, -1);
int temp = num;
while (num > 0) {
int &&temp = num % 10;
vec.push_back(temp);
num /= 10;
}
auto size = vec.size();
for (int i = size - 1; i >= 0; --i)
latest[vec[i]] = i;
for (int i = size - 1; i >= 0; --i) {
for (int j = 9; j > vec[i]; --j) {
if (latest[j] != -1 && i > latest[j]) {
swap(vec[i], vec[latest[j]]);
return support(vec);
}
}
}
return temp;
}
int support(vector<int> &vec) {
int ret = 0;
while (!vec.empty()) {
ret = ret * 10 + vec.back();
vec.pop_back();
}
return ret;
}
};