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

  • 相关阅读:
    P1064 金明的预算方案
    P1164 小A点菜
    P1346 电车
    01背包二进制优化
    2018暑期多校1
    牛课第二次多校I
    STL
    Reachability from the Capital
    P2921 [USACO08DEC]在农场万圣节Trick or Treat on the Farm
    P3387 【模板】缩点
  • 原文地址:https://www.cnblogs.com/loadofleaf/p/5001619.html
Copyright © 2011-2022 走看看