Leetcode-31題:Next Permutation

題目:

Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).

The replacement must be in-place, do not allocate extra memory.

Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1

分析:如果數(shù)組從大到小有序,則當(dāng)前為最大,只需轉(zhuǎn)為從小到大排序即可。如果不是,那么此時需從右至左掃描找到第一個num[i]>nums[i-1]的下標(biāo),在i-1右邊選出比nums[i-1]大的最小的數(shù)交換,然后從小到大將i-1之后的數(shù)字排序即可。

代碼:

def pop_sort(self,nums,l,r):
    for i in range(0,r-l):
        for j in range(l,r-i):
            if nums[j] > nums[j+1]:
                nums[j],nums[j+1] = nums[j+1],nums[j]

def nextPermutation(self, nums):
    """
    :type nums: List[int]
    :rtype: void Do not return anything, modify nums in-place instead.
    """
    n = len(nums)
    i = n-1
    while i>0 and nums[i]<=nums[i-1]:
        i -= 1
    if i == 0:
        self.pop_sort(nums,0,n-1)
    else:
        j = n-1
        while nums[j] <= nums[i-1]:
            j -= 1
        nums[j],nums[i-1] = nums[i-1],nums[j]
        self.pop_sort(nums,i,n-1)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容