标签:
题目来源
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]
题目思路
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)
[LeetCode]题解(python):031-Next Permutation
标签:
原文地址:http://www.cnblogs.com/loadofleaf/p/5001619.html