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.

分析:
先找到每个digit出现的最后位置。
然后从左到右,看是否有9到当前digit的另一个digit在当前digit的后面出现过,如果出现过,果断换。
 1 class Solution {
 2     public int maximumSwap(int num) {
 3         char[] digits = Integer.toString(num).toCharArray();
 4         Map<Integer, Integer> map = new HashMap<>();
 5         for (int i = 0; i < digits.length; i++) {
 6             // if there are digits with the same value, we choose the last one.
 7             // 27367 -> 77362
 8             map.put(digits[i] - '0', i);
 9         }
10         
11         for (int i = 0; i < digits.length; i++) {
12             for (int k = 9; k > digits[i] - '0'; k--) {
13                 if (map.getOrDefault(k, - 1) > i) {
14                     char tmp = digits[i];
15                     digits[i] = digits[map.get(k)];
16                     digits[map.get(k)] = tmp;
17                     return Integer.valueOf(new String(digits));
18                 }
19             }
20         }
21         
22         return num;
23     }
24 }

 

posted @ 2021-03-29 05:18  北叶青藤  阅读(27)  评论(0编辑  收藏  举报