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:
 21

Example 2:

Input:
 21

Output:
 -1

Analysis

寻找next permutation,如果把全部permutation找出来是很耗时的,全排列需要O(n!)的时间和空间复杂度。因此需要一些比较特殊的处理。

Solution

Next Permutation完全一样的步骤。

来自LeetCode Official 四段步骤处理:

  1. 从右往左搜索到第一个 a[i] > a[i - 1]

  2. a[i]的右侧搜索比a[i - 1]大的最小的数a[j]

  3. 交换a[ i - 1], a[j]

  4. 排序从i到末尾(nums.length)的数字,按照升序

By @sanketdige268

Reference

https://leetcode.com/problems/next-greater-element-iii/solution/

https://leetcode.com/problems/next-greater-element-iii/discuss/101843/Java-Solution-like-Next-Permutation-Problem-O(n\

Last updated

Was this helpful?