Next Greater Element III

这道题看穿了的话其实质就是Next permutation而已,所以这里只需要调用next permutation的函数再加输入做一些格式转换就行了,另外题目要求是32bit整数,所以最后还必须加上一行结果数是不是在这个范围的判断即可,下面是代码

class Solution(object):
    def nextGreaterElement(self, n):
        """
        :type n: int
        :rtype: int
        """
        nums = [int(x) for x in str(n)]
        self.nextPermutation(nums)
        result = int(''.join([str(x) for x in nums]))
        return result if result > n and result < 2**31 else -1

    def nextPermutation(self, nums):
        flag = True
        n = len(nums)
        st, ed = 0, n - 1

        for i in xrange(ed, 0, -1):
            if nums[i] > nums[i - 1] and flag:
                pos = self.find(nums, nums[i - 1], i, ed)
                nums[pos], nums[i - 1] = nums[i - 1], nums[pos]
                self.reverse(nums, i, ed)
                flag = False
                break

        if flag:
            nums.reverse()

    def find(self, nums, base, start, end):
        result = None
        compare = sys.maxint
        for i in xrange(start, end + 1):
            if nums[i] - base > 0 and nums[i] - base <= compare:
                compare = nums[i] - base
                result = i
        return result

    def reverse(self, nums, start, end):
        while start <= end:
            nums[start], nums[end] = nums[end], nums[start]
            start += 1
            end -= 1

results matching ""

    No results matching ""