share my java solution!


  • 0
    T

    Main idea is that sort num array, and compare the sorted num with original num to find the first different element, then find the original index of the current element of the sorted num in the original num array, and swap it with current element in the original num. Then we can just return it!

    class Solution {
        public int maximumSwap(int num) {
            String str = String.valueOf(num);
            char[] array = str.toCharArray();
            Map<Character,Integer> map = new HashMap<>();
            for(int i=0;i<array.length;i++){
                map.put(array[i],i);
            }
            char[] copy = new char[array.length];
            for(int i=0;i<array.length;i++){
                copy[i]=array[i];
            }
            
            Arrays.sort(copy);
            reverse(copy);
            if(str.equals(new String(copy))){
                return num;
            }
            
            for(int i=0;i<array.length;i++){
                if(array[i]!=copy[i]){
                    int j = map.get(copy[i]);
                    swap(array,i,j);
                    break;
                }
            }
            
            
            return Integer.parseInt(new String(array));
            
        }
        
        public void reverse(char[] array){
            int i = 0;
            int j = array.length-1;
            while(i<j){
                char c = array[i];
                array[i] = array[j];
                array[j] = c;
                i++;
                j--;
            }
        }
        
        public void swap(char[] array,int i,int j){
            char c = array[i];
            array[i]=array[j];
            array[j]=c;
        }
    }
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.