zoukankan      html  css  js  c++  java
  • 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);
        }
      }
    };
  • 相关阅读:
    文档视图
    引入缓冲池技术
    数据库访问与查询
    OnInitialUpdate函数
    显示股票视图的全局函数
    切换视图的核心代码
    GuiEdit的使用
    操作方法
    SQL 使用 解析
    调用API 实现 窗体 拖动
  • 原文地址:https://www.cnblogs.com/ethanhong/p/10289442.html
Copyright © 2011-2022 走看看