Java, simple solution with inline explanation


  • 0

    This is essentially the same as next permutation.

        private void swap(char[] nums, int i, int j) {
            char tmp = nums[i];
            nums[i] = nums[j];
            nums[j] = tmp;
        }
        public int nextGreaterElement(int n) {
            char[] nums = (n+"").toCharArray();
            int i, j;
            for (i = nums.length-2; i >= 0; i--) {  //find the first descending pair (backwards)
                if (nums[i] < nums[i+1]) break;
            }
            if (i < 0) return -1;
            for (j = i+1; j+1 < nums.length && nums[j+1] > nums[i]; j++);   //find ceiling of nums[i]
            swap(nums, i, j);   //replace ith with jth
            i = i+1;
            j = nums.length-1;
            while (i < j) swap(nums, i++, j--); //reverse i+1 to nums.length-1
            long result = Long.parseLong(new String(nums));
            if (result > Integer.MAX_VALUE) return -1;
            return (int) result;
        }
    

Log in to reply
 

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