Given a positive 32-bit integer n, you need to find the smallest 32-bit integer which have exact Ly the same digits existing in the integer n and was greater in value than N. If no such positive 32-bit integer exists, you need to return-1.
Example 1:
Input: Output: 21
Example 2:
Input: Output: 1
Reprint Annotated Source: http://www.cnblogs.com/wdfwolf3/, thank you.
Time complexity O (n), spatial complexity O (n), 5ms.
Public intNextgreaterelement (intN) { //if it is a 1-bit integer, return 1 directly, plus 10 and one if(N <= 11){ return-1; } //convert to char array for easy handling of numbers Char[] Nums = (n+ ""). ToCharArray (); inti = Nums.length-2; //find the first ascending number of digits from the forward for(; I >= 0; i--) { if(Nums[i] < nums[i+1]) { Break; } } //If none exists, return-1 if(I < 0){ return-1; } intj = Nums.length-1; //find the first larger number from the back, so that it is the smallest value in all the numbers greater than I for(; j > i; j--) { if(Nums[i] <Nums[j]) { Break; } } //exchanging numbers for i,j positions CharTMP =Nums[i]; Nums[i]=Nums[j]; NUMS[J]=tmp; //sort the numbers after I, making the results minimalArrays.sort (Nums, I, nums.length); //It is possible to cross out after swapping, using a long type to judge LongAns = Long.parselong (NewString (nums)); return(ans>integer.max_value)?-1: ((int) ans); }
Leetcode556--next Greater Element III (JAVA)