Week 3-2. [Heap] 215. Kth Largest Element in an Array (Python3)
๋ฌธ์ ํด๊ฒฐ ๊ณผ์
โ๏ธ ๋ฌธ์ ์์ฝ
Kth Largest Element in an Array - LeetCode
Can you solve this real interview question? Kth Largest Element in an Array - Given an integer array nums and an integer k, return the kth largest element in the array. Note that it is the kth largest element in the sorted order, not the kth distinct eleme
leetcode.com
โก๏ธ ์ฃผ์ด์ง ๋ฐฐ์ด์ ์ ๋ ฌํ์ง ์๊ณ k๋ฒ์งธ๋ก ํฐ ์๋ฅผ ๋ฐํํ๋ผ.
๐ ์ด๋ค ์์ผ๋ก ์ ๊ทผํ๋๊ฐ?
์ ๋ ฌ์ ํ์ง ๋ง๋ผ๋ ์๊ตฌ์ฌํญ์ด ์์์ผ๋ฏ๋ก ์ต๋ํ์ ์ฌ์ฉํ์.
์ฐ์ ํ์ด์ฌ์์ ์ ๊ณตํ๋ ํ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ฅผ ์ฌ์ฉํด ํ์ด๋ณด๊ณ , ํ์ ์ง์ ๊ตฌํํด์๋ ํ์ด๋ณผ ๊ฒ์ด๋ค.
ํ์ด์ฌ์์ ์ ๊ณตํ๋ ํ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ ์ต์ํ์ด๊ธฐ ๋๋ฌธ์ ๋ง์ด๋์ค ๊ธฐํธ๋ฅผ ์ด์ฉํด ์ต๋ํ์ฒ๋ผ ๋์ํ๊ฒ ํ ์ ์๋ค.
ํ์ ์ง์ ๊ตฌํํ ๋๋ push์ pop์ ๊ตฌํํด์ผ ํ๋๋ฐ, ๊ฐ๊ฐ์์ ์ฌ์ฉ๋๋ bubbleUp๊ณผ bubbleDown ๋ก์ง์ด ํต์ฌ์ด๋ค.
๐ฏ ํ์ด
ํ์ด์ฌ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ฅผ ์ฌ์ฉํ ํ์ด์ด๋ค.
import heapq as hq
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
lst = [] # ํ์ ๋ชจ๋ฐฉํ ๋ฆฌ์คํธ
for x in nums:
hq.heappush(lst, -x) # ์ต๋ํ
ans = 0
for x in range(k):
ans = -hq.heappop(lst)
return ans
ํ์ ์ง์ ๊ตฌํํ์ฌ ์ฌ์ฉํ ํ์ด์ด๋ค.
class Heap:
def __init__(self):
self.array = []
self.numberOfItems = 0
def push(self, e: int) -> None:
self.array.append(e) # ์๋ก์ด ์์๋ฅผ ๋งจ ๋ง์ง๋ง์ ์ ์ฅ
self.bubbleUp(self.numberOfItems) # Heap์ ๋งจ ๋ง์ง๋ง ์์์ธ array[numberOfItems]๋ถํฐ bubble Up!
self.numberOfItems += 1
def bubbleUp(self, i: int) -> None:
child, parent = i, (i-1)//2
if parent >= 0 and self.array[child] > self.array[parent]:
self.array[child], self.array[parent] = self.array[parent], self.array[child] # swap
self.bubbleUp(parent)
def pop(self) -> int:
mx = self.array[0]
self.array[0] = self.array[self.numberOfItems-1] # ๋ง์ง๋ง ์์๋ฅผ 0๋ฒ์งธ ์ธ๋ฑ์ค์ ์ ์ฅ
self.numberOfItems -= 1
self.bubbleDown(0) # # Heap์ ์ฒซ ๋ฒ์งธ ์์์ธ array[0]๋ถํฐ bubble Down!
return mx
def bubbleDown(self, i: int) -> None: # i๋ ๋ถ๋ชจ ์ธ๋ฑ์ค
left, right = 2*i+1, 2*i+2 # ์ผ์ชฝ ์์, ์ค๋ฅธ์ชฝ ์์
if left <= self.numberOfItems - 1:
# ๋ ์ค ๋ ํฐ ์์ ์ ํ
if right <= self.numberOfItems and self.array[right] > self.array[left]:
left = right
# ์์์ ์ ํ๋ ์์์ด ๋ถ๋ชจ๋ณด๋ค ํฌ๋ค๋ฉด swap
if self.array[i] < self.array[left]:
self.array[i], self.array[left] = self.array[left], self.array[i] # swap
self.bubbleDown(left)
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
heap = Heap()
for x in nums:
heap.push(x)
ans = 0
for i in range(k):
ans = heap.pop()
return ans
๋ค๋ฅธ ์ฌ๋์ ์ฝ๋๋ฅผ ํ๊ตฌํด๋ณด๊ธฐ
ํ์ด์ฌ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ฅผ ์ด์ฉํ ํ์ด์ด๋ฉฐ heapify()๋ฅผ ์ฌ์ฉํด ๊ธฐ์กด nums ๋ฆฌ์คํธ๋ฅผ ์ต์ํ์ผ๋ก ๋ณํํ์ฌ ์ด์ฉํ๋ค.
import heapq as hq
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
hq.heapify(nums) # nums๋ฅผ ์ต์ํ์ผ๋ก ๋ณํ
amount = len(nums)
while amount > k:
hq.heappop(nums)
amount -= 1
return nums[0]