• LC 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.
    

    Note:

    1. The given number is in the range [0, 108]
     

    Runtime: 4 ms, faster than 86.08% of C++ online submissions for Maximum Swap.

    //
    // Created by yuxi on 2019-01-18.
    //
    #include <vector>
    #include <algorithm>
    #include <unordered_map>
    using namespace std;
    
    class Solution {
    private:
      unordered_map<int,vector<int>> mp;
    public:
      int getret(vector<int>& a){
        int ret = 0;
        for(int i=0; i<a.size(); i++){
          ret = ret * 10 + a[i];
        }
        return ret;
      }
      int maximumSwap(int num) {
        int savenum = num;
        vector<int> numa;
        while(num > 0){
          numa.push_back(num%10);
          num /= 10;
        }
        reverse(numa.begin(), numa.end());
        for(int i=0; i<numa.size();i++) mp[numa[i]].push_back(i);
        if(numa.size() == 1) return numa[0];
        helper(numa, 0);
        return getret(numa);
      }
      void helper(vector<int>& a, int idx) {
        if(idx == a.size()) return ;
        int maxval = INT_MIN, maxidx = 0;
        for(int i=idx; i<a.size(); i++) {
          if(maxval < a[i]) {
            maxval = a[i];
            maxidx = i;
          }
        }
        if(maxval != a[idx]) {
          int tmp = a[idx];
          a[idx] = maxval;
          a[maxidx] = tmp;
          if(mp[maxval].size() != 1 && mp[maxval].back() > maxidx) {
            a[mp[maxval].back()] = tmp;
            a[maxidx] = maxval;
          }
          return;
        } else {
          helper(a, idx+1);
        }
      }
    };
  • 相关阅读:
    docker基础总结
    python基础学习总结
    静默(命令行)安装oracle 11g
    java中如果函数return可能抛出异常怎么办
    Android 开发先驱的博客列表
    栈与队列
    线性表
    算法
    数据结构概论
    iOS开发中实现手势解锁
  • 原文地址:https://www.cnblogs.com/ethanhong/p/10289442.html
Copyright © 2020-2023  润新知