Advertisement
1988coder

556. Next Greater Element III

Dec 24th, 2018
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.83 KB | None | 0 0
  1. /*
  2. Very similar to: https://leetcode.com/problems/next-permutation/
  3. Refer: https://leetcode.com/submissions/detail/176366402/
  4.  
  5. Time Complexity: O(N)
  6. Space Complexity: O(N)
  7.  
  8. N = number of digits in n... its max 10 (Integer Max).
  9. Thus, time complexity can be O(1) and space complexity can be O(1).
  10. */
  11. class Solution {
  12.     public int nextGreaterElement(int n) {
  13.         if (n < 12) {
  14.             return -1;
  15.         }
  16.        
  17.         // Converting digits of n into character array.
  18.         char[] numChar = String.valueOf(n).toCharArray();
  19.        
  20.        
  21.         // Starting from right side, find the first digit that is smaller to its right neighbour.
  22.         int i = numChar.length - 1;
  23.         while (i > 0 && numChar[i-1] >= numChar[i]) {
  24.             i--;
  25.         }
  26.        
  27.         if (i == 0) {
  28.             return -1;
  29.         }
  30.        
  31.         // For the previous found digit, find the next greater digit on the right and swap them.
  32.         int j = numChar.length - 1;
  33.         while (j >= i && numChar[j] <= numChar[i-1]) {
  34.             j--;
  35.         }
  36.         swap(numChar, i-1, j);
  37.        
  38.         // Reverse all the digits before the (i-1) digit.
  39.         // (No need to sort as all the digits on right are sorted in descending order).
  40.         reverse(numChar, i);
  41.        
  42.         try {
  43.             return Integer.parseInt(new String(numChar));
  44.         } catch (Exception e) {
  45.             return -1;
  46.         }
  47.     }
  48.    
  49.     private void reverse(char[] charArr, int start) {
  50.         int end = charArr.length - 1;
  51.         while (start < end) {
  52.             swap(charArr, start, end);
  53.             start++;
  54.             end--;
  55.         }
  56.     }
  57.    
  58.     private void swap(char[] charArr, int i, int j) {
  59.         char temp = charArr[i];
  60.         charArr[i] = charArr[j];
  61.         charArr[j] = temp;
  62.     }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement