[LeetCode] 556. Next Greater Element III

下一个更大的元素III。版本三其实跟前两个版本几乎没什么关系,是一道找next permutation的题。题意是给一个整数,请找出Integer范围内用到相同数字但是比当前数字大的数字。例子,

Example 1:

Input: 12
Output: 21

Example 2:

Input: 21
Output: -1

如果想看怎么跑例子可以参见next permutation

时间O(n)

空间O(1) - 因为创建的数组最多只有32位,并不随着input变大

Java实现

 1 class Solution {
 2     public int nextGreaterElement(int n) {
 3         char[] res = ("" + n).toCharArray();
 4         int i = res.length - 2;
 5         while (i >= 0 && res[i + 1] <= res[i]) {
 6             i--;
 7         }
 8         if (i < 0) {
 9             return -1;
10         }
11         int j = res.length - 1;
12         while (j >= 0 && res[j] <= res[i]) {
13             j--;
14         }
15         swap(res, i, j);
16         reverse(res, i + 1);
17         long val = Long.parseLong(new String(res));
18         return val <= Integer.MAX_VALUE ? (int) val : -1;
19     }
20 
21     private void swap(char[] chars, int i, int j) {
22         char temp = chars[i];
23         chars[i] = chars[j];
24         chars[j] = temp;
25     }
26 
27     private void reverse(char[] chars, int start) {
28         int i = start;
29         int j = chars.length - 1;
30         while (i < j) {
31             swap(chars, i++, j--);
32         }
33     }
34 }

猜你喜欢

转载自www.cnblogs.com/aaronliu1991/p/12501777.html