-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path670.maximum-swap.cpp
76 lines (75 loc) · 1.48 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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/*
* @lc app=leetcode id=670 lang=cpp
*
* [670] Maximum Swap
*
* https://leetcode.com/problems/maximum-swap/description/
*
* algorithms
* Medium (40.62%)
* Total Accepted: 42.7K
* Total Submissions: 105K
* Testcase Example: '2736'
*
*
* Given a non-negative integer, you could swap two digits at most once to get
* the maximum valued number. Return the maximum valued number you could get.
*
*
* Example 1:
*
* Input: 2736
* Output: 7236
* Explanation: Swap the number 2 and the number 7.
*
*
*
* Example 2:
*
* Input: 9973
* Output: 9973
* Explanation: No swap.
*
*
*
*
* Note:
*
* The given number is in the range [0, 108]
*
*
*/
class Solution {
public:
int maximumSwap(int num) {
if(num/10 == 0) return num;
vector<int> vec;
vector<int> numvec;
int numm = num;
numvec.push_back(num%10);
vec.push_back(0); num/=10;
int i = 1;
while(num){
numvec.push_back(num%10);
if(num%10 > numvec[vec.back()])
vec.push_back(i);
else
vec.push_back(vec.back());
num/=10;
i++;
}
i = vec.size();i--;
while(i-1>=0){
if(numvec[i] < numvec[vec[i-1]]){
swap(numvec[i], numvec[vec[i-1]]);
break;
}
i--;
}
int ans = 0;
reverse(numvec.begin(), numvec.end());
for(auto const& c: numvec)
ans = ans*10+c;
return ans;
}
};