Advertisement
1988coder

670. Maximum Swap

Feb 10th, 2019
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.36 KB | None | 0 0
  1. // LeetCode URL: https://leetcode.com/problems/maximum-swap/
  2.  
  3. /**
  4.  * Greedy Approach
  5.  *
  6.  * Use buckets to record the last position of digit 0 ~ 9 in this num.
  7.  *
  8.  * Loop through the num array from left to right. For each position, we check
  9.  * whether there exists a larger digit in this num (start from 9 to current
  10.  * digit). We also need to make sure the position of this larger digit is behind
  11.  * the current one. If we find it, simply swap these two digits and return the
  12.  * result.
  13.  *
  14.  * Time Complexity: O(9 * N) = O(N)
  15.  *
  16.  * Space Complexity: O(10) = O(1)
  17.  *
  18.  * N = Number of digits in the input number.
  19.  */
  20. class Solution {
  21.     public int maximumSwap(int num) {
  22.         if (num <= 11) {
  23.             return num;
  24.         }
  25.         char[] digits = Integer.toString(num).toCharArray();
  26.  
  27.         int[] lastIdx = new int[10];
  28.  
  29.         for (int i = 0; i < digits.length; i++) {
  30.             lastIdx[digits[i] - '0'] = i;
  31.         }
  32.  
  33.         for (int i = 0; i < digits.length; i++) {
  34.             for (int k = 9; k > digits[i] - '0'; k--) {
  35.                 if (lastIdx[k] > i) {
  36.                     char tmp = digits[i];
  37.                     digits[i] = digits[lastIdx[k]];
  38.                     digits[lastIdx[k]] = tmp;
  39.                     return Integer.valueOf(new String(digits));
  40.                 }
  41.             }
  42.         }
  43.  
  44.         return num;
  45.     }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement