#### 题目

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 and use only constant 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

#### 思路

class Solution {
func nextPermutation(_ nums: inout [Int]) {
guard nums.count > 2 else {
rev(&nums, low: 0, high: nums.count - 1)
return
}

let end = nums.count - 2
var k: Int?
var l: Int?
for index in (0...end).reversed() {
if nums[index] < nums[index+1] {
k = index
break
}
}

if k == nil {
rev(&nums, low: 0, high: nums.count - 1)
return
}

for index in ((k!+1)...(nums.count-1)).reversed() {
if nums[index] > nums[k!] {
l = index
break
}
}

nums.swapAt(k!, l!)
rev(&nums, low: k!+1, high: nums.count - 1)
}

private func rev(_ nums: inout [Int], low: Int, high: Int) {
var _low = low
var _high = high
while _low < _high {
nums.swapAt(_low, _high)
_low += 1
_high -= 1
}
}
}