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.
题目大意:给定一个非负的数字,交换数字中的两位,得到最大的数。
思路:见代码注释
代码:
package Array; /** * @Author OovEver * @Date 2017/11/28 10:10 */ public class Solution { public int maximumSwap(int num) { char[] digits = String.valueOf(num).toCharArray(); int[] buckets = new int[10]; for(int i=0;i<digits.length;i++) { // 找出每个数字最后出现的位置 buckets[digits[i] - '0'] = i; } for(int i=0;i<digits.length;i++) { // 从后向当前digits遍历buckets,找出大于当前digits[i]的数 for(int j=9;j>digits[i]-'0';j--) { // 大于digits[i]数的索引必须大于digits[i]的索引 if (buckets[j] > i) { char temp = digits[i]; digits[i] = digits[buckets[j]]; digits[buckets[j]] = temp; return Integer.valueOf(new String(digits)); } } } return num; } }