Skip to content

Instantly share code, notes, and snippets.

@syphh
Created March 6, 2023 13:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save syphh/89cba8d748a5095b0211883e455e21a9 to your computer and use it in GitHub Desktop.
Save syphh/89cba8d748a5095b0211883e455e21a9 to your computer and use it in GitHub Desktop.
# 1st approach:
def kth_largest(arr, k):
for i in range(k-1):
arr.remove(max(arr))
return max(arr)
# 2nd approach:
def kth_largest(arr, k):
n = len(arr)
arr.sort()
return arr[n-k]
# 3rd approach:
import heapq
def kth_largest(arr, k):
arr = [-elem for elem in arr]
heapq.heapify(arr)
for i in range(k-1):
heapq.heappop(arr)
return -heapq.heappop(arr)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment