首页 > 其他 > 详细

leetcode - Maximum Swap

时间:2017-09-20 09:50:09      阅读:257      评论:0      收藏:0      [点我收藏+]

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存在不属于他的位置(换句话说, 就是比他的的数字在他的后面), 那么我们就要swap。

这个想法就会引导我们想要记录digit和相对应的index,所以我们就有两个可以用的: hashmap 和 array  

这里我们选数组 int[] numberToIndex, numberToIndex的index代表digit,value对应digit存在的index, 所以size 应该就是10 代表0->9 所有可能的数字

345 -> numberToIndex[3] : 0;  numberToIndex[4] : 1, numberToIndex[5] : 2   

这题的关键点在于, 我们要把所有在numberToIndex中比当前digit大的数字所在index跟当前digit的index进行比较 (从最大的开始,9),一旦找到一个前者index大的,那么我们就swap,并且return,结束。 我们看到那些number中不存在的digit会被intialize为0,不会影响结果。 

============代码===============

 1     public int maximumSwap(int sum) {
 2         String str = sum + "";
 3         int[] numberToIndex = new int[10];
 4         int i = 0;
 5         for (char chara : str.toCharArray()) {
 6             numberToIndex[chara - ‘0‘] = i++;
 7         }    
 8         int j = 0;
 9         while (j < str.length()) {
10             int current = str.charAt(j) - ‘0‘;
11             for (int number = 9; number > current; number--) {
12                 int indexOfLarge = numberToIndex[number];
13                 if (j < indexOfLarge) {
14                     int newNum = swap(j, indexOfLarge, str, str.charAt(j));
15                     return newNum;
16                 }
17             }
18             j++;
19         }
20         return sum;
21     }

 

leetcode - Maximum Swap

原文:http://www.cnblogs.com/shuaih/p/7558919.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!