-
Notifications
You must be signed in to change notification settings - Fork 388
Expand file tree
/
Copy paths1.cpp
More file actions
22 lines (22 loc) · 687 Bytes
/
Copy paths1.cpp
File metadata and controls
22 lines (22 loc) · 687 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// OJ: https://leetcode.com/problems/maximum-swap/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
public:
int maximumSwap(int num) {
string digits = to_string(num), memo(digits.size(), '\0');
int maxIndex = digits.size() - 1;
for (int i = digits.size() - 1; i >= 0; --i) {
if (digits[i] > digits[maxIndex]) maxIndex = i;
memo[i] = maxIndex;
}
for (int i = 0; i < digits.size(); ++i) {
if (memo[i] > i && digits[i] != digits[memo[i]]) {
swap(digits[i], digits[memo[i]]);
return stoi(digits);
}
}
return num;
}
};