031 Next Permutation

又是一道纯数学的题, 纸上认真研究下就好。 这道题需要Inplace, 所以写了个辅助的reverse.

class Solution:
    # @param {integer[]} nums
    # @return {void} Do not return anything, modify nums in-place instead.
    def nextPermutation(self, nums):
        length = len(nums)
        l = length - 1
        while l >= 1 and nums[l] <= nums[l-1]:
            l -= 1
        if l == 0:
            self.reverse(nums, 0, length - 1)
        else:
            j = length - 1
            while nums[j] <= nums[l-1]:
                j -= 1
            nums[l-1], nums[j] = nums[j], nums[l-1]
            self.reverse(nums, l, length - 1)
        print(nums)

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

 

posted @ 2015-07-09 06:36  dapanshe  阅读(147)  评论(0编辑  收藏  举报