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]

解题思路:

要交换两个数字的来构成一个最大的数字,第一个想法就是交换高位的小数字a和低位的比这个小数字大最多的b。

那我们就要找到这个数子右边的最大数字。

可以首先将数字转换成字符串然后再用一个字符串存储该位置右边包含自己的最大数字。

然后我们从原数字字符串的高位向低位开始遍历,找到一个位置,它右边包含自己的最大数字不是它自己。

然后我们从低位向高位开始再遍历找这个数字:因为我们想把小的数字放在尽可能低的位置。

代码:

class Solution {
public:
    int maximumSwap(int num) {
        string numStr = to_string(num), back = numStr;
        for(int i = back.size() - 2; i >= 0; i--){
            back[i] = max(back[i],back[i+1]);
        }
        for(int i = 0; i < numStr.size(); i++){
            if(numStr[i] == back[i])
                continue;
            for(int j = numStr.size() - 1; j < numStr.size(); j--){
                if(back[i] == numStr[j]){
                    swap(numStr[j], numStr[i]);
                    return stoi(numStr);
                }
            }
        }
        return stoi(numStr);
    }
};
原文地址:https://www.cnblogs.com/yaoyudadudu/p/9196895.html