-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path670.cpp
More file actions
53 lines (49 loc) · 1004 Bytes
/
Copy path670.cpp
File metadata and controls
53 lines (49 loc) · 1004 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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include "common.h"
using namespace std;
class Solution {
public:
int maximumSwap(int num) {
int temp = num;
vector<int> n;
while (num) {
n.push_back(num % 10);
num /= 10;
}
std::reverse(n.begin(), n.end());
if (n.size() <= 1) {
return temp;
}
int l = 0, r = 0;
// find first reverse pair
for (int i = 1; i < n.size(); ++i) {
if (n[i] > n[i - 1]) {
l = i - 1;
r = i;
break;
}
}
if (r != 0) {
// found reverse pair, then find largest num after pair
for (int i = r + 1; i < n.size(); ++i) {
if (n[i] >= n[r]) {
r = i;
}
}
}
// find most left num smaller than n[r]
while (l > 0 && n[l - 1] < n[r]) {
l -= 1;
}
std::swap(n[l], n[r]);
int rst = 0;
for (int i = 0; i < n.size(); ++i) {
rst = rst * 10 + n[i];
}
return rst;
}
};
int main() {
Solution s;
cout << s.maximumSwap(2736) << endl;
return 0;
}