[LeetCode] 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]

给定一个正整数,要求最多交换一次,使这个数最大。
思路:
如果要交换两个数,可以使用swap函数,这就需要将将num转化成整数数组或者字符串数组,方便起见利用to_string函数将num转换成字符串数组。
因为如果要使交换后的数字最大,应该找出距离首位最近的的那个值(小于最大值)与距离首位最远的那个最大值。所以使用字符串逆序遍历,找出对应值及其索引。
最后判断如果给定num不需要交换,则返回num。否则交换找出的数字后返回即可。

class Solution {
public:
    int maximumSwap(int num) {
        string str = to_string(num);
        int maxVal = -1, maxIdx = -1, leftIdx = -1, rightIdx = -1;
        for (int i = str.size() - 1; i >= 0; i--) {
            if (str[i] > maxVal) {
                maxVal = str[i];
                maxIdx = i;
            }
            if (str[i] < maxVal) {
                leftIdx = i;
                rightIdx = maxIdx;
            }
        }
        if (leftIdx == -1)
            return num;
        swap(str[leftIdx], str[rightIdx]);
        return stoi(str);
    }
};
// 3 ms
原文地址:https://www.cnblogs.com/immjc/p/7803169.html