Skip to content

Instantly share code, notes, and snippets.

@derekli66
Created April 10, 2022 13:45
Show Gist options
  • Save derekli66/06aa6aac5018b94ce96120062a2eed09 to your computer and use it in GitHub Desktop.
Save derekli66/06aa6aac5018b94ce96120062a2eed09 to your computer and use it in GitHub Desktop.
The solution to the LeetCode problem, 1046. Last Stone Weight, https://leetcode.com/problems/last-stone-weight/
class MaxHeap {
private var array = Array<Int>()
func leftChild(_ i:Int) -> Int {
return 2*i+1
}
func rightChild(_ i:Int) -> Int {
return 2*i+2
}
func parent(_ i:Int) -> Int {
return Int(floor(Float(i - 1)/2.0))
}
func insert(_ val: Int) {
array.append(val)
var index = array.count - 1
while index > 0 {
let par = parent(index)
if array[par] < array[index] {
array.swapAt(par, index)
index = par
}
else {
break
}
}
}
private func heapify() {
var index = 0
var largest = 0
while index < array.count {
let left = leftChild(index)
let right = rightChild(index)
if left < array.count && array[largest] < array[left] {
largest = left
}
if right < array.count && array[largest] < array[right] {
largest = right
}
if largest == index {
break
}
else {
array.swapAt(largest, index)
index = largest
}
}
}
func pop() -> Int {
let topValue = array.first!
array.swapAt(0, array.count - 1)
array.removeLast()
heapify()
return topValue
}
func peak() -> Int {
return array.first!
}
func count() -> Int {
return array.count
}
func rawContent() -> Array<Int> {
return array
}
}
class Solution {
func lastStoneWeight(_ stones: [Int]) -> Int {
let maxHeap = MaxHeap()
for stone in stones {
maxHeap.insert(stone)
}
while maxHeap.count() > 1 {
let y = maxHeap.pop()
let x = maxHeap.pop()
let diff = y - x
if diff > 0 {
maxHeap.insert(diff)
}
}
return maxHeap.count() > 0 ? maxHeap.peak() : 0
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment