LeetCode - Next Permutation
阿新 • • 發佈:2018-01-04
in-place num possible anything locate imp ascend list mod
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
=======================================
My own solve:
class Solution(object): def nextPermutation(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.""" l0 = len(nums) if l0==2: if nums[1]>nums[0]: temp = nums[0] nums[0]=nums[1] nums[1]=temp elif l0>2: l1 = l0-3 flag = 0 while l1>=0: k=0 while (l0-k-l1)>=2: (arr,i)= self.subSort(nums[l1:l0-k]) if arr != []: nums[l1:l0-k] = arr ss = nums[l1+i+1:] ss.sort() nums[l1+i+1:]=ss flag = 1 break k += 1 if flag == 1: break l1 -= 1 if flag == 0: nums.sort() def subSort(self, arr): l = len(arr) while l>=2: l1 = l while l1>= 1: if arr[l-1] > arr[l1-1]: temp = arr[l1-1] arr[l1-1] = arr[l-1] arr[l-1] = temp return(arr,l1-1) l1 -= 1 l -= 1 return ([],0)
Others(http://bookshadow.com/weblog/2016/09/09/leetcode-next-permutation/):
解題思路:
首先從右向左遍歷數組,找到第一個相鄰的左<右的數對,記右下標為x,則左下標為x - 1
若x > 0,則再次從右向左遍歷數組,直到找到第一個大於nums[x - 1]的數字為止,記其下標為y,交換nums[x - 1], nums[y]
最後將nums[x]及其右邊的元素就地逆置
class Solution(object): def nextPermutation(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ size = len(nums) for x in range(size - 1, -1, -1): if nums[x - 1] < nums[x]: break if x > 0: for y in range(size - 1, -1, -1): if nums[y] > nums[x - 1]: nums[x - 1], nums[y] = nums[y], nums[x - 1] break for z in range((size - x) / 2): nums[x + z], nums[size - z - 1] = nums[size - z - 1], nums[x + z]
LeetCode - Next Permutation