Question
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.
Solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
public int maximumSwap(int num) { char[] digit = Integer.toString(num).toCharArray(); int[] pos = new int[10]; for (int i = 0; i < digit.length; i++) pos[digit[i]-'0'] = i; for (int i = 0; i < digit.length; i++) for (int j = 9; j > digit[i]-'0'; j--) { if (pos[j] > i) { char tmp = digit[i]; digit[i] = (char)(j+'0'); digit[pos[j]] = tmp; return Integer.valueOf(new String(digit)); } } return num; }
|