LintCode 1095 Maximum Swap 数字处理好题

1095 · Maximum Swap
Algorithms
Medium

Description
Given a non-negative integer. You could choose to swap two digits of it. Return the maximum valued number you could get.

Only $39.9 for the “Twitter Comment System Project Practice” within a limited time of 7 days!

WeChat Notes Twitter for more information(WeChat ID jiuzhang998)

The given number is in the range of [0, 10^8]

Example
Example 1:

Input: 2736
Output: 7236
Explanation: Swap the number 2 and the number 7.
Example 2:

Input: 9973
Output: 9973
Explanation: No swap.

解法1:
我的方法感觉不是最优,至少空间上不是。
首先把num存到digits数组里面。然后sort。如下所示。
num = 98386
digits=6 8 3 8 9
sortedDigits=3 6 8 8 9
然后从n-1到0比较digits[]和sortedDigits[],发现3和8不一样,那么我们就在digits[]里面,找下标最小的那个8.
例如9838628 ->8 2 6 8 3 8 9->3 2 6 8 8 8 9
而不是找接下来的那个8,那就是8 2 6 3 8 8 9,结果不对。

class Solution {
public:
    /**
     * @param num: a non-negative intege
     * @return: the maximum valued number
     */
    int maximumSwap(int num) {
        // Write your code here
        vector<int> digits;
        int num2 = num;
        while (num2) {
            digits.push_back(num2 % 10);
            num2 /= 10;
        }
        if (digits.size() < 2) return num;
        vector<int> sortedDigits(digits);
        sort(sortedDigits.begin(), sortedDigits.end());
        for (int i = digits.size() - 1; i >= 0; i--) {
            if (digits[i] != sortedDigits[i]) {
                for (int j = 0; j <= i; j++) {
                    if (digits[j] == sortedDigits[i]) {
                        swap(digits[i], digits[j]);
                        break;
                    }
                }
                break;
            }
        }
        int res = 0;
        for (int i = digits.size() - 1; i >= 0; i--) {
            res = res * 10 + digits[i];
        }
        return res;
    }
};

解法2:硬算。这种方法好。时间复杂度和空间复杂度都是O(n)。

class Solution {
public:
    /**
     * @param num: a non-negative intege
     * @return: the maximum valued number
     */
    int maximumSwap(int num) {
        // Write your code here
        string numStr = to_string(num);
        int n = numStr.size();
        unordered_map<int, int> mp;
        for (int i = 0; i < n; i++) {
            mp[numStr[i] - '0'] = i;
        }
        for (int i = 0; i < n; i++) {
            for (int j = 9; j >= 0; j--) {
                if (j > (numStr[i] - '0') && mp[j] > i) {
                    swap(numStr[i], numStr[mp[j]]);
                    return stoi(numStr);
                }
            }
        }
        return stoi(numStr);
    }
};
  • 7
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值