Leetcode 556.下一个更大元素III
下一个更大元素III
给定一个32位正整数 n,你需要找到最小的32位整数,其与 n 中存在的位数完全相同,并且其值大于n。如果不存在这样的32位整数,则返回-1。
示例 1:
输入: 12
输出: 21
示例 2:
输入: 21
输出: -1
C++: using next permutation
int nextGreaterElement(int n) { auto digits = to_string(n); next_permutation(begin(digits), end(digits)); auto res = stoll(digits); return (res > INT_MAX || res <= n) ? -1 : res; } |
Java
1 import java.util.Arrays; 2 3 public class Solution { 4 public int nextGreaterElement(int n) { 5 char[] number = (n + "").toCharArray(); 6 7 int i, j; 8 // I) Start from the right most digit and 9 // find the first digit that is 10 // smaller than the digit next to it. 11 for (i = number.length-1; i > 0; i--) 12 if (number[i-1] < number[i]) 13 break; 14 15 // If no such digit is found, its the edge case 1. 16 if (i == 0) 17 return -1; 18 19 // II) Find the smallest digit on right side of (i-1)'th 20 // digit that is greater than number[i-1] 21 int x = number[i-1], smallest = i; 22 for (j = i+1; j < number.length; j++) 23 if (number[j] > x && number[j] <= number[smallest]) 24 smallest = j; 25 26 // III) Swap the above found smallest digit with 27 // number[i-1] 28 char temp = number[i-1]; 29 number[i-1] = number[smallest]; 30 number[smallest] = temp; 31 32 // IV) Sort the digits after (i-1) in ascending order 33 Arrays.sort(number, i, number.length); 34 35 long val = Long.parseLong(new String(number)); 36 return (val <= Integer.MAX_VALUE) ? (int) val : -1; 37 } 38 }