Created
July 10, 2022 15:21
-
-
Save derekli66/4de463bba458566238bd0372d55c046a to your computer and use it in GitHub Desktop.
The solution to LeetCode problem, https://leetcode.com/problems/kth-largest-element-in-an-array/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
func findKthLargest(_ nums: [Int], _ k: Int) -> Int { | |
if nums.count < k { return 0 } | |
let minHeap = MinHeap() | |
for idx in 0..<k { | |
minHeap.insert(nums[idx]) | |
} | |
for idx in k..<nums.count { | |
if nums[idx] > minHeap.peak() { | |
_ = minHeap.pop() | |
minHeap.insert(nums[idx]) | |
} | |
} | |
return minHeap.peak() | |
} | |
} | |
private class MinHeap { | |
private var array = Array<Int>() | |
private func leftChild(_ i:Int) -> Int { | |
return 2*i+1 | |
} | |
private func rightChild(_ i:Int) -> Int { | |
return 2*i+2 | |
} | |
private 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 smallest = 0 | |
while index < array.count { | |
let left = leftChild(index) | |
let right = rightChild(index) | |
if left < array.count && array[smallest] > array[left] { | |
smallest = left | |
} | |
if right < array.count && array[smallest] > array[right] { | |
smallest = right | |
} | |
if smallest == index { | |
break | |
} | |
else { | |
array.swapAt(smallest, index) | |
index = smallest | |
} | |
} | |
} | |
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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment