【Leetcode】031Next 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 and use only constant extra memory.
Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.

说实在话这题刚开始没有看明白意思,其实后来也没看懂,最后写出来的代码是根据solution自己复现的。
这一题的要求就是,给你一个array,你给出这些元素的下一个全排列。这里不知道全排列的排列规律就没法做。


例子

1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1


2019-06-08

看了solution这题的解题思路如下:
031

代码如下:

class Solution(object):


    def nextPermutation(self, nums):
        """
        :type nums: List[int]
        :rtype: None Do not return anything, modify nums in-place instead.
        """
        if len(nums)<3:
            return nums.reverse()

        def swap(list,left_side, right_side):
            tmp = nums[right_side]
            nums[right_side] = nums[left_side]
            nums[left_side] = tmp
            return nums

        for i in range(len(nums)-1,-1,-1):
            if nums[i-1]<nums[i]:
                first_point = i-1	#找到逆序第一个不满足nums[i-1]>num[i]的点
                for j in range(len(nums)-1,first_point,-1):
                    if nums[j]>nums[first_point]:
                        second_point = j	#逆序找到first_point之后最后一个比它大的值
                        #print(nums[second_point])
                        swap(nums,first_point,second_point)	#交换位置
                        nums[first_point+1:] = sorted(nums[first_point+1:])	#后续位置重排列
                        #print(nums)
                        break
                break

S = Solution()
# nums = [1,2]
# nums = [1,5,8,4,7,6,5,3,1]
# nums = [3,2,1]
# nums = [1,3,2]
# nums = [1,2,3]
# nums = [1,1,5]
nums =[2,2,0,4,3,1]
S.nextPermutation(nums)


结果分析

第一次时间空间消耗排名如此靠前!

Runtime: 16 ms, faster than 99.85% of Python online submissions for Next Permutation.
Memory Usage: 11.6 MB, less than 98.17% of Python online submissions for Next Permutation.


注意事项

基本思路动态图已经很直观了,在实现的时候还是有好些地方出错,主要就是慢慢调试吧。我调试过程中几个要注意的点:

  1. 从后往前找第一个不满足不满足nums[i-1]>num[i]的指针时,只找逆序的第一个,在这个if语句后加上break
  2. for j in range(len(nums)-1,first_point,-1):找到第一个不满足nums[i-1]>num[i]得到first-point指针后,在后面的元素中逆序遍历找到第一个大于nums[first_point]的点,要注意的就是python中逆序遍历时·for … range()·的用法,其中第二个参数意味着从后往前遍历到还剩n+1个元素停下。
  3. 在某一次测试中有测试样例nums =[2,2,0,4,3,1]不通过,这里也需要加上break
  4. 元素只有两个时,上述代码无法解决nums = [1,2]这样的样例。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值