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();
    }
};
posted on 2017-09-03 11:11  Beserious  阅读(407)  评论(0编辑  收藏  举报