forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
NextPermutation.swift
51 lines (43 loc) · 1.34 KB
/
NextPermutation.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/**
* Question Link: https://leetcode.com/problems/next-permutation/
* Primary idea: Traverse the number from right to left, and replace the first smaller one
* with the least bigger one, then reverse all number afterwards
*
* Time Complexity: O(n), Space Complexity: O(1)
*
*/
class NextPermutation {
func nextPermutation(_ nums: inout [Int]) {
guard nums.count > 0 else {
return
}
var violate = -1
// find violate
for i in stride(from: nums.count - 1, to: 0, by: -1) {
if nums[i] > nums[i - 1] {
violate = i - 1
break
}
}
if violate != -1 {
for i in stride(from: nums.count - 1, to: violate, by: -1) {
if nums[i] > nums[violate] {
swap(&nums, i, violate)
break
}
}
}
reverse(&nums, violate + 1, nums.count - 1)
}
func reverse<T>(_ nums: inout [T], _ start: Int, _ end: Int) {
var start = start, end = end
while start < end {
swap(&nums, start, end)
start += 1
end -= 1
}
}
func swap<T>(_ nums: inout [T], _ p: Int, _ q: Int) {
(nums[p], nums[q]) = (nums[q], nums[p])
}
}