Fast and easy python solution (beaten 79%)


  • 0
    G

    Detail analysis and explanation could be found at http://www.guaguagua.net/?p=51, written by Chinese.

    def re_order(self, a, start, end):
        for i in range(0, (end - start + 1) // 2):
            a[start + i], a[end - i] = a[end - i], a[start + i]
    
    def nextPermutation(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        pos = -1
        le = len(nums)
        for i in range(le - 1, 0, -1):  # le-1..1
            if nums[i] > nums[i - 1]:
                pos = i - 1
                break
        if pos == -1:
            self.re_order(nums, 0, le - 1)
            return
        for i in range(le - 1, -1, -1):  # le-1..0
            if nums[pos] < nums[i]:
                nums[pos], nums[i] = nums[i], nums[pos]
                self.re_order(nums, pos + 1, le - 1)
                break

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.