Skip to content

Commit 37bcbee

Browse files
committed
Refactor solution to Next Permutation
1 parent 6266047 commit 37bcbee

File tree

1 file changed

+21
-21
lines changed

1 file changed

+21
-21
lines changed

Array/NextPermutation.swift

Lines changed: 21 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -9,36 +9,36 @@
99

1010
class NextPermutation {
1111
func nextPermutation(_ nums: inout [Int]) {
12-
guard let violateIndex = findViolate(nums) else {
12+
guard let violateIdx = findViolate(nums) else {
1313
nums.reverse()
1414
return
1515
}
16-
17-
swap(&nums, violateIndex, findLeastGreater(nums, violateIndex))
18-
nums = nums[0...violateIndex] + nums[(violateIndex + 1)...].reversed()
16+
17+
swap(&nums, findFirstGreater(nums, violateIdx), violateIdx)
18+
nums[(violateIdx + 1)...].reverse()
19+
}
20+
21+
private func findFirstGreater(_ nums: [Int], _ violateIdx: Int) -> Int {
22+
for i in ((violateIdx + 1)..<nums.count).reversed() {
23+
if nums[i] > nums[violateIdx] {
24+
return i
25+
}
26+
}
27+
28+
return -1
1929
}
20-
21-
fileprivate func findViolate(_ nums: [Int]) -> Int? {
30+
31+
private func findViolate(_ nums: [Int]) -> Int? {
2232
for i in (1..<nums.count).reversed() {
2333
if nums[i] > nums[i - 1] {
2434
return i - 1
2535
}
2636
}
27-
37+
2838
return nil
2939
}
30-
31-
fileprivate func findLeastGreater(_ nums: [Int], _ violateIndex: Int) -> Int {
32-
for i in (violateIndex + 1..<nums.count).reversed() {
33-
if nums[i] > nums[violateIndex] {
34-
return i
35-
}
36-
}
37-
38-
fatalError()
39-
}
40-
41-
fileprivate func swap<T>(_ nums: inout [T], _ indexL: Int, _ indexR: Int) {
42-
(nums[indexL], nums[indexR]) = (nums[indexR], nums[indexL])
40+
41+
private func swap(_ nums: inout [Int], _ l: Int, _ r: Int) {
42+
(nums[l], nums[r]) = (nums[r], nums[l])
4343
}
44-
}
44+
}

0 commit comments

Comments
 (0)