题目描述:
LeetCode 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.
Example 1:
Input: 12 Output: 21
Example 2:
Input: 21 Output: -1
题目大意:
给定一个32位正整数n,寻找大于n,并且所含数字与n中各位数字相等的最小32位正整数。若不存在,返回-1。
解题思路:
本题目是Next Permutation的变形,参考Next Permutation的解法。
Python代码:
class Solution(object):
def nextGreaterElement(self, n):
"""
:type n: int
:rtype: int
"""
nums = list(str(n))
size = len(nums)
for x in range(size - 1, -1, -1):
if nums[x - 1] < nums[x]:
break
if x > 0:
for y in range(size - 1, -1, -1):
if nums[y] > nums[x - 1]:
nums[x - 1], nums[y] = nums[y], nums[x - 1]
break
for z in range((size - x) / 2):
nums[x + z], nums[size - z - 1] = nums[size - z - 1], nums[x + z]
ans = int(''.join(nums))
return n < ans <= 0x7FFFFFFF and ans or -1
本文链接:http://bookshadow.com/weblog/2017/04/09/leetcode-next-greater-element-iii/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。