1. 程式人生 > 實用技巧 >556. Next Greater Element III

556. Next Greater Element III

Given a positive32-bitintegern, you need to find the smallest32-bitinteger which has exactly the same digits existing in the integernand is greater in value than n. If no such positive32-bitinteger exists, you need to return -1.

Example 1:

Input: 12
Output: 21

Example 2:

Input: 21
Output: -1
class
Solution { public int nextGreaterElement(int n) { char[] ch = (n + "").toCharArray(); int le = ch.length; int i = le - 1; while(i > 0 && ch[i - 1] >= ch[i]) i--; if(i == 0) return -1; i--; int j = le - 1; while
(j > i && ch[j] <= ch[i]) j--; swap(ch, i, j); reverse(ch, i + 1); long val = Long.parseLong(new String(ch)); return (val <= Integer.MAX_VALUE) ? (int) val : -1; } public void swap(char[] ch, int i, int j) { char tmp = ch[i]; ch[i]
= ch[j]; ch[j] = tmp; } public void reverse(char[] ch, int i) { int j = ch.length - 1; while(i < j) { swap(ch, i, j); i++; j--; } } }

啊這,不就是next permutation嗎,小樣換了個馬甲照樣認識你