-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathContents.swift
More file actions
112 lines (93 loc) · 2.44 KB
/
Contents.swift
File metadata and controls
112 lines (93 loc) · 2.44 KB
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
import UIKit
struct Stack<T> {
private var internalArray = Array<T>()
mutating func push(_ element: T) {
self.internalArray.append(element)
}
@discardableResult
mutating func pop() -> T? {
guard !self.isEmpty else { return nil }
return internalArray.remove(at: internalArray.count-1)
}
var top: T? {
guard !self.isEmpty else { return nil }
return internalArray[internalArray.count-1]
}
var count: Int {
return internalArray.count
}
var isEmpty: Bool {
return internalArray.isEmpty
}
}
struct Queue<T> {
private var internalArray = Array<T>()
mutating func enqueue(_ element: T) {
self.internalArray.insert(element, at: 0)
}
@discardableResult
mutating func dequeue() -> T? {
guard !self.isEmpty else { return nil }
return self.internalArray.remove(at: count-1)
}
var head: T? {
guard !self.isEmpty else { return nil }
return self.internalArray[count-1]
}
var tail: T? {
guard !self.isEmpty else { return nil }
return self.internalArray[0]
}
var count: Int {
return internalArray.count
}
var isEmpty: Bool {
return internalArray.isEmpty
}
}
struct Fish {
let weight: Int
let direction: Int
}
// ¯\_(ツ)_/¯
// 25% performance
public func solution(_ A : inout [Int], _ B : inout [Int]) -> Int {
var queue = Queue<Fish>()
zip(A, B).forEach { weight, direction in
queue.enqueue(Fish(weight: weight, direction: direction))
}
var stack = Stack<Fish>()
while !queue.isEmpty {
// Adding the first fish
if stack.isEmpty {
stack.push(queue.dequeue()!)
continue
}
// Same direction
if queue.head!.direction == stack.top!.direction {
stack.push(queue.dequeue()!)
continue
}
// If goes upsteam we add it to the stack
if queue.head!.direction == 1 {
stack.push(queue.dequeue()!)
continue
}
// Different directions
if queue.head!.weight > stack.top!.weight {
stack.pop()
} else {
queue.dequeue()
}
}
return stack.count
}
var A = [4, 3, 2, 1, 5]
var B = [0, 1, 0, 0, 0]
solution(&A, &B)
A = [3, 3]
B = [1, 0]
solution(&A, &B)
A = [3, 4, 2, 5]
B = [1, 0, 1, 0]
solution(&A, &B)