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. 

解析:

最终的目标是:找到一个最右侧最大的可交换的数字,与左侧小于该数字的值进行交换,如:

a: 2736 -> 7236

b: 9918 -> 9981

c: 9198 -> 9918

d: 9876 -> 9876

 

1. 将正整数切割成字符数组,方便操作

2. 记录起始标志位 from=0,表示从下标0开始找,记录是否发生过交换swap=false,表示还未发生交换

3. 从标志位(from)开始,从左往右找最右边的一个最大的数字和下标,如:89291,得到结果 max=9,maxIndex=3

4. 从标志位(from)到maxIndex找第一个非max值的元素下标,得到结果i=2

5. 交换i=2和maxIndex=3的位置

6. 将结果组装整数,返回result

7. 如果没有发生交换,说明当前最大值是不需要交换的,将from设置成maxIndex+1的位置,重新再走一遍逻辑

源码(Java):

class Solution {
    public int maximumSwap(int num) {
        char[] chars = String.valueOf(num).toCharArray();
        int len = chars.length;

        //先找最大数的值和下标,需要找最右侧的最大值
        int from = 0;
        boolean swap = false;
        while (from < len -1 && swap == false) {
char max = '0'; int maxIndex = -1; for (int i = from; i < len; i++) { char t = chars[i]; if (max <= t) { max = t; maxIndex = i; } } //再从左向右找第一个不等于最大值,并交换值 for (int i = from; i < maxIndex; i++) { char t = chars[i]; if (t != max) { //找到了,需要交换值 chars[maxIndex] = chars[i]; chars[i] = max; swap = true; break; } } if (!swap){ from = maxIndex+1; } } int result = chars[0] - '0'; for (int i = 1; i < len; i++) { result = result * 10 + (chars[i] - '0'); } return result; } }

 

posted @ 2019-01-10 14:26  ronghantao  阅读(901)  评论(0编辑  收藏  举报