-
Notifications
You must be signed in to change notification settings - Fork 0
/
670.hpp
42 lines (35 loc) · 939 Bytes
/
670.hpp
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
#ifndef LEETCODE_670_HPP
#define LEETCODE_670_HPP
#include <iostream>
#include <queue>
#include <algorithm>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <set>
#include <numeric>
#include <stack>
#include <string>
using namespace std;
class Solution {
public:
int maximumSwap(int num) {
string numString = to_string(num);
vector<int> maxPos(numString.size());
int n = static_cast<int>(numString.size());
int curMaxPos = n - 1;
for (int i = n - 1; i >= 0; --i) {
if (numString[i] > numString[curMaxPos])
curMaxPos = i;
maxPos[i] = curMaxPos;
}
for (int j = 0; j < n; ++j) {
if (numString[maxPos[j]] != numString[j]) {
swap(numString[j], numString[maxPos[j]]);
break;
}
}
return stoi(numString);
}
};
#endif //LEETCODE_670_HPP