Skip to content

Instantly share code, notes, and snippets.

@joanromano
Created September 15, 2019 07:27
Show Gist options
  • Save joanromano/d434455b3be7180195ae20db85bfcdc0 to your computer and use it in GitHub Desktop.
Save joanromano/d434455b3be7180195ae20db85bfcdc0 to your computer and use it in GitHub Desktop.
An array based implementation of a Monoqueue
struct Monoqueue<T: Comparable> {
var array = [(value: T, count: Int)]()
var max: T {
return array.first!.value
}
mutating func push(_ value: T) {
var count = 0
while !array.isEmpty, array.last!.value < value {
count += array.last!.count + 1;
array.removeLast()
}
array.append((value: value, count: count))
}
mutating func pop() {
if array.first!.count > 0 {
array[0] = (value: array[0].value, count: array[0].count-1)
} else {
_ = array.removeFirst()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment