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();
    }
};

相关文章:

  • 2021-05-07
  • 2021-08-23
  • 2021-10-14
  • 2021-08-06
  • 2021-08-01
  • 2021-08-19
  • 2021-08-12
猜你喜欢
  • 2021-08-14
  • 2022-12-23
  • 2022-12-23
  • 2021-04-06
  • 2021-08-22
  • 2021-10-10
  • 2022-12-23
相关资源
相似解决方案