[LeetCode]题解(python):031-Next Permutation

时间:2021-04-06 06:22:20

题目来源


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)


 _author_ = "YE"
# -*- coding:utf-8 -*-
class Solution(object):
def nextPermutation(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
#print(nums)
len1 = len(nums)
index = -1
for i in range(len1 - 1):
if nums[len1 - 1 - i] > nums[len1 - i - 2]:
index = len1 - 1 - i
break
if index == -1:
nums.sort()
else:
minindex = index
minvalue = nums[index]
for i in range(len1 - index - 1):
if minvalue > nums[index + i + 1] > nums[index - 1]:
minindex = index + i + 1
minvalue = nums[minindex] nums[minindex] = nums[index - 1]
nums[index - 1] = minvalue #sort other numbers from index
numbers = len1 - index
#print(numbers)
for i in range(numbers - 1):
print('I:',i)
for j in range(numbers - i - 1):
if nums[len1 - j - 1] < nums[len1 - j - 2]:
temp = nums[len1 - j - 1]
nums[len1 - j - 1] = nums[len1 - j - 2]
nums[len1 - j - 2] = temp #print(minindex, minvalue)
#print(nums)