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

分析:如果数组从大到小有序,则当前为最大,只需转为从小到大排序即可。如果不是,那么此时需从右至左扫描找到第一个num[i]>nums[i-1]的下标,在i-1右边选出比nums[i-1]大的最小的数交换,然后从小到大将i-1之后的数字排序即可。

代码:

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)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容