My Java solution with explanation in comments (3ms)


  • 1
        public int nextGreaterElement(int n) {
    
            char[] cArr = String.valueOf(n).toCharArray();
    
            // i is the leftmost digit that should be exchanged
            int i = cArr.length - 1;
            while (i > 0 && cArr[i] <= cArr[i-1]) i--;
    
            if (i <= 0) return -1;
    
            // j is the digit that should be exchanged with digit at i
            int j = cArr.length - 1;
            while (j >= i && cArr[j] <= cArr[i-1]) j--;
    
            // Exchange the digits at location i and j
            char tmp = cArr[j];
            cArr[j] = cArr[i-1];
            cArr[i-1] = tmp;
    
            // Sort the digits from location i to the end
            Arrays.sort(cArr, i, cArr.length);
    
            try {
               return Integer.parseInt(String.valueOf(cArr));
            } catch (Exception e) {
                // Intentionally left blank
            }
            return -1;
        }
    

  • 0
    S

    @RunRunCode
    Hi I ran your code and want to discuss about one test case
    Input : 1999999
    Expected Output: -1

    Your output: 9199999

    Can you explain why the leetcode test case is expecting wrong result when your answer is correct ?

    Url https://gist.github.com/anonymous/74c0c73802361ee89fe73a3b48967ea6


Log in to reply
 

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