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

猜你喜欢

转载自www.cnblogs.com/ethanhong/p/10289442.html