556. Next Greater Element III
题目描述
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 integer n and is greater in value than n. If no such positive 32-bit integer exists, you need to return -1.
|
|
|
|
题目大意
给一数值n
,满足以下条件的值 ans
:
- 不大于
0x7FFFFFFF
- 大于n
- ans包含n中所有的数。
符合条件则返回ans,否则返回-1。
解题思路
转n为数组。
反向遍历数组,找到最后一个递增下标index
。
如果存在递增下标,则反向遍历数组,将nums[index - 1]
,与最后一个大于nums[index - 1]
进行替换。
由于index
之后的元素呈递减序列,所以采用双指针的方式交换元素。
代码
|
|