Java O(n) solution 9ms


  • 0
    M
        public int maximumSwap(int num) {
            char[] ch = (num + "").toCharArray();
            
            int[] largest = new int[ch.length];
            largest[ch.length - 1] = ch[ch.length - 1] - '0';
            for (int i = ch.length - 2; i >= 0; i--) {
                largest[i] = Math.max(largest[i + 1], ch[i] - '0');
            }
    
            int i = 0;
            while (i < ch.length) {
                if (largest[i] != ch[i] - '0') {
                    for (int j = ch.length - 1; j > i; j--) {
                        if (ch[j] - '0' == largest[i]) {
                        	char tmp = ch[j];
                            ch[j] = ch[i];
                            ch[i] = tmp;
                            break;
                        }
                    }                
                    return Integer.parseInt(String.valueOf(ch));
                }
                i++;
            }
            return num;
        }
    }
    

Log in to reply
 

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