zoukankan      html  css  js  c++  java
  • 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();
        }
    };
    
  • 相关阅读:
    Vue小实例
    Bootstrap进度条
    Bootstrap导航栏
    Bootstrap表单
    java date类
    正则表达式(java)规则大全
    正则表达式(java)
    java Stringbuffer类
    java String类
    object类
  • 原文地址:https://www.cnblogs.com/pk28/p/7469097.html
Copyright © 2011-2022 走看看