leetcode 670. Maximum Swap
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.
题题目要求交换两位数字,使得原来的数字变得尽量打。
思路 :暴力枚举交换的位置,取最大的就行
class Solution {
public:
int maximumSwap(int num) {
vector<int> v;
set<int> s;
s.insert(num);
while (num) {
v.push_back(num%10);
num /= 10;
}
for (int i = 0; i < v.size(); i++) {
for (int j = i+1; j < v.size(); j++) {
swap(v[i], v[j]);
int tmp = 0;
for (int k = v.size()-1; k >= 0; k--) {
tmp = tmp*10+v[k];
}
s.insert(tmp);
swap(v[i], v[j]);
}
}
return *s.rbegin();
}
};
原文地址:http://www.cnblogs.com/pk28/
与有肝胆人共事,从无字句处读书。
欢迎关注公众号:
欢迎关注公众号: