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值为一对升序数中较大的下标
while index > 0 {
if nums[index-1] < nums[index] { break }
index -= 1
}
//如果没有下一个排列,index为0
if index == 0 {
sort(&nums, fromIndex: 0)
return
}
//在index往后的数字里(降序)找到第一个比[index-1]大的数,下标为exchangeIndex
var exchangeIndex = nums.count - 1
while exchangeIndex > index {
if nums[exchangeIndex] > nums[index-1] { break }
exchangeIndex -= 1
}
//交换这两个数
swap(&nums[index-1], &nums[exchangeIndex])
//index及其后的数字重新按升序排列。
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]