11、Next Permutation

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]
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容