670. Maximum Swap
Given a non-negative integer, you could swap two digits in most once to get the maximum number. Return the maximum valued number to 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.
Given a nonnegative number, swap the two digits in the number to get the maximum number.
Idea: See code comments
Code:
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++) {
// Find the last position of each number
Buckets[digits[i]-' 0 ' = i;
}
for (int i=0;i<digits.length;i++) {
// digits traverse buckets from back to current, find number greater than current digits[i] for
(int j=9;j> digits[i]-' 0 '; j--) {
// greater than digits[i] number must be greater than Digits[i index
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;
}
}