zoukankan      html  css  js  c++  java
  • [LeetCode]题解(python):031-Next Permutation


    题目来源


    https://leetcode.com/problems/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.


    题意分析


    Input:一个数组

    Output:一个数组(原地操作)

    Conditions:输出数组是输入数组的下一个比输入大的数组。 如[1, 2, 3] => [1, 3, 2]

                     如果输入的是最大的,那么输出最小的数组。    如[3, 2, 1]  => [1, 2, 3]


     题目思路


    1. 从后往前找第一个比前面大的数字,若是不存在,则已经是最大的数组,直接原地升序排序(list.sort())返回
    2. 若是找到最大的值,记录其位置index,然后在index之后(包括index)找一个比nums[index - 1]大的最小值,并将其与nums[index - 1]交换
    3. 对index之后(包括index)的nums数组元素进行冒泡排序

     AC代码(Python)


     1 _author_ = "YE"
     2 # -*- coding:utf-8 -*-
     3 class Solution(object):
     4     def nextPermutation(self, nums):
     5         """
     6         :type nums: List[int]
     7         :rtype: void Do not return anything, modify nums in-place instead.
     8         """
     9         #print(nums)
    10         len1 = len(nums)
    11         index = -1
    12         for i in range(len1 - 1):
    13             if nums[len1 - 1 - i] > nums[len1 - i - 2]:
    14                 index = len1 - 1 - i
    15                 break
    16         if index == -1:
    17             nums.sort()
    18         else:
    19             minindex = index
    20             minvalue = nums[index]
    21             for i in range(len1 - index - 1):
    22                 if  minvalue > nums[index + i + 1] > nums[index - 1]:
    23                     minindex = index + i + 1
    24                     minvalue = nums[minindex]
    25 
    26             nums[minindex] = nums[index - 1]
    27             nums[index - 1] = minvalue
    28 
    29             #sort other numbers from index
    30             numbers = len1 - index
    31             #print(numbers)
    32             for i in range(numbers - 1):
    33                 print('I:',i)
    34                 for j in range(numbers - i - 1):
    35                     if nums[len1 - j - 1] < nums[len1 - j - 2]:
    36                         temp = nums[len1 - j - 1]
    37                         nums[len1 - j - 1] = nums[len1 - j - 2]
    38                         nums[len1 - j - 2] = temp
    39 
    40             #print(minindex, minvalue)
    41         #print(nums)
    View Code

  • 相关阅读:
    Ubuntu16.04下安装virtualbox,配置及卸载
    机器学习1-线性回归
    python中的数据结构-链表
    Numpy 对于矩阵的操作持续更新
    ubuntu16.04 下同时打开多个终端窗口
    matlab mashgrid 函数
    站立会议04
    站立会议03
    第一次冲刺--站立会议02
    第一次冲刺--站立会议01
  • 原文地址:https://www.cnblogs.com/loadofleaf/p/5001619.html
Copyright © 2011-2022 走看看