Leetcode--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:
The given number is in the range [0, 108]
只交换一次整数中的两个数,获得最大的值

思路

从高位向低扫描,如果后面某位的数大于等于当前位的值,交换位置后即得到最大值。

代码

class Solution {
public:
    ///整型数组转int
    int toInt(int* arr, int n){
        int res = 0;
        for(int i=0; i10 + arr[i];
        }
        return res;
    }

    int maximumSwap(int num) {
        ///首先获得每一位数字的数组
        int arr[20] = {0};
        int back = num, n = 0;
        while(back){
            arr[n++] = back % 10;
            back /= 10;
        }
        for(int i=0, j=n-1; i///从高位向低位扫描
        for(int i=0; iint maxn = arr[i];
            int index = i;
            for(int j=i+1; jif(arr[j] >= maxn){
                    index = j;
                    maxn = arr[j];
                }
            }
            if(maxn > arr[i]){
                swap(arr[i], arr[index]);
                return toInt(arr, n);
            }
        }
        return num;
    }
};

你可能感兴趣的:(数据结构及算法)