Problem Description
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
Code
class Solution {
func nextPermutation(inout nums: [Int]) {
// 插入排序
func sort(inout nums: [Int], fromIndex: Int) {
for i in fromIndex+1..<nums.count {
let key = nums[i]
var j = i - 1
while j>=fromIndex && nums[j] > key {
nums[j+1] = nums[j]
j -= 1
}
nums[j+1] = key
}
}
var index = nums.count - 1
//從右邊開始找到第一個不是降序的下標。index值為一對升序數(shù)中較大的下標
while index > 0 {
if nums[index-1] < nums[index] { break }
index -= 1
}
//如果沒有下一個排列,index為0
if index == 0 {
sort(&nums, fromIndex: 0)
return
}
//在index往后的數(shù)字里(降序)找到第一個比[index-1]大的數(shù),下標為exchangeIndex
var exchangeIndex = nums.count - 1
while exchangeIndex > index {
if nums[exchangeIndex] > nums[index-1] { break }
exchangeIndex -= 1
}
//交換這兩個數(shù)
swap(&nums[index-1], &nums[exchangeIndex])
//index及其后的數(shù)字重新按升序排列。
sort(&nums, fromIndex: index)
}
}
var array = [4,3,2,1,0,0,0,0]
let solution = Solution()
solution.nextPermutation(&array) //[0, 0, 0, 0, 1, 2, 3, 4]