您的位置:首页 > 编程语言 > Python开发

LeetCode 31. Next Permutation

2016-11-04 22:00 453 查看
题目:

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

题意:

给定一个数列,找出在比该序列大的集合中最小的序列,作为下一次排序。

如果该序列已经是最大,则将最小的序列作为下一次排序。

题解:

找出所有可置换序列:

比如:在[1,3,2]中, 可置换序列为[0,1];[0,2]

在[3,1,2]中,可置换序列为[1,2]

由于置换序列第一位下标代表会置换的地方,则该值越大越好(离个位越近)

所以找出可置换序列的第一位下标为最大元素的序列,

在第一位为最大元素的序列可能有多个,

就需要对比第二位元素,所以,找出第一位元素值最大,第二位元素索引对应在所给数列的值最小的那个序列。

然后将其交换,最后对第二位元素后面的序列进行排序拼接即可。

class Solution(object):
def nextPermutation(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
temp=[]
max_num = []
temp[:] = nums
nums_len = len(nums)
temp.sort()
max_num = temp[::-1]
if nums == max_num:  #序列最大的情况
nums.sort()
else:
record = []
for i in range(nums_len):
for j in range(i+1,nums_len):
if nums[nums_len-1-i] > nums[nums_len-1-j]:
record.append([nums_len-1-j,nums_len-1-i]) #记录所有可置换序列
break
record.sort()
max_flag = record[len(record)-1][0]  #需要交换的第一位
switch_flag = record[len(record)-1][1]  #需要交换的第二位初始化
for i in range(len(record)):
if record[i][0] == max_flag and nums[switch_flag]>nums[record[i][1]]:  #找出真正需要交换的序列
switch_flag = record[i][1]
switch = nums[max_flag]   #交换nums中的2个元素
nums[max_flag] = nums[switch_flag]
nums[switch_flag] = switch
former = []
later = []
for i in range(nums_len):
if i <= max_flag:
former.append(nums[i])  #前面不需要变动的元素
else:
later.append(nums[i])  #后续需要排序的元素
later.sort()
nums[:] = former + later
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Python leetcode