-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
969 Pancake Sorting.swift
59 lines (48 loc) · 1.38 KB
/
969 Pancake Sorting.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
52
53
54
55
56
57
58
59
//
// 969 Pancake Sorting.swift
// LeetCode-Solutions
//
// Created by Aleksandar Dinic on 29/08/2020.
// Copyright © 2020 Aleksandar Dinic. All rights reserved.
//
import Foundation
/// Source: https://leetcode.com/problems/pancake-sorting/
class Solution {
/// Sorts the array performing a series of pancake flips.
///
/// - Parameter A: The array of integers.
/// - Returns: Sorted array.
///
/// - Complexity:
/// - time: O(n^2), where n is the length of the array of integers.
/// - space: O(n), where n is the length of the array of integers.
func pancakeSort(_ A: [Int]) -> [Int] {
var ans = [Int]()
var nums = A
for i in (1...nums.count).reversed() {
var index = -1
for j in 0..<nums.count {
guard nums[j] == i else { continue }
index = j
break
}
guard index != i - 1 else { continue }
if index != 0 {
ans.append(index + 1)
flip(&nums, index + 1)
}
ans.append(i)
flip(&nums, i)
}
return ans
}
private func flip(_ nums: inout [Int], _ end: Int) {
var start = 0
var end = end - 1
while start < end {
nums.swapAt(start, end)
start += 1
end -= 1
}
}
}