Next Greater Element III
Medium
Given a positive 32-bit integer n, you need to find the smallest 32-bit integer which has exactly the same digits existing in the integernand is greater in value than n. If no such positive 32-bit integer exists, you need to return -1.
Example 1:
Input:
12
Output:
21Example 2:
Input:
21
Output:
-1Analysis
寻找next permutation,如果把全部permutation找出来是很耗时的,全排列需要O(n!)的时间和空间复杂度。因此需要一些比较特殊的处理。
Solution
和Next Permutation完全一样的步骤。
来自LeetCode Official 四段步骤处理:
从右往左搜索到第一个
a[i] > a[i - 1]在
a[i]的右侧搜索比a[i - 1]大的最小的数a[j]交换
a[ i - 1],a[j]排序从
i到末尾(nums.length)的数字,按照升序
Reference
https://leetcode.com/problems/next-greater-element-iii/solution/
Last updated
Was this helpful?