LeetCode – 31. Next Permutation

題目連結: https://leetcode.com/problems/next-permutation/

// Test cases:
// input: [1,2,3], output: [1,3,2]
// input: [3,2,1], output: [1,2,3]
// input: [1,1,5], output: [1,5,1]
// input: [1,2,4,3], output: [1,3,2,4]
func nextPermutation(_ nums: inout [Int]) {
    var i = nums.count - 2
    while i >= 0 && nums[i] >= nums[i+1] {
        i -= 1
    }
    
    if i == -1 {
        nums.sort()
    } else {
        var j = nums.count - 1
        while j > i && nums[j] <= nums[i] {
            j -= 1
        }
        nums.swapAt(i, j)
        
        var left = (i + 1)
        var right = nums.count - 1
        while left < right {
            nums.swapAt(left, right)
            left += 1
            right -= 1
        }
    }
}