forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
NextPermutation.swift
44 lines (37 loc) · 1.18 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
/**
* 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 let violateIdx = findViolate(nums) else {
nums.reverse()
return
}
swap(&nums, findFirstGreater(nums, violateIdx), violateIdx)
nums[(violateIdx + 1)...].reverse()
}
private func findFirstGreater(_ nums: [Int], _ violateIdx: Int) -> Int {
for i in ((violateIdx + 1)..<nums.count).reversed() {
if nums[i] > nums[violateIdx] {
return i
}
}
return -1
}
private func findViolate(_ nums: [Int]) -> Int? {
for i in (1..<nums.count).reversed() {
if nums[i] > nums[i - 1] {
return i - 1
}
}
return nil
}
private func swap(_ nums: inout [Int], _ l: Int, _ r: Int) {
(nums[l], nums[r]) = (nums[r], nums[l])
}
}