물음표 살인마의 개발블로그

알고리즘 문제/Leetcode

215. Kth Largest Element in an Array

BEstyle 2023. 1. 25. 07:23

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 element.

You must solve it in O(n) time complexity.

 

Example 1:

Input: nums = [3,2,1,5,6,4], k = 2
Output: 5

Example 2:

Input: nums = [3,2,3,1,2,4,5,5,6], k = 4
Output: 4

 

Constraints:

  • 1 <= k <= nums.length <= 105
  • -104 <= nums[i] <= 104

#https://leetcode.com/problems/kth-largest-element-in-an-array/description/

'''
1. 아이디어 :
    1)  heapq를 사용할 수 있다
    2)  배열을 정렬할 수 있다.
2. 시간복잡도 :
    1)  O(n) + O(k log n) = O(n log k)
    2)  O(n) = O(nlogn)
    * 이론상 최악의 경우, 1)번이 더 빠르지만, 실제로는 2)번이 더 빠르다
3. 자료구조 :
    1)  heapq
    2)  배열
'''

#1)
class Solution:
    def findKthLargest(self, nums: List[int], k: int) -> int:
        ans = []
        for num in nums:
            ans.append([-num,num])
        heapq.heapify(ans)
        for i in range(k-1):
            heapq.heappop(ans)
        return ans[0][1]

#2)
# class Solution:
#     def findKthLargest(self, nums: List[int], k: int) -> int:
#         return sorted(nums, reverse=True)[k-1]

'알고리즘 문제 > Leetcode' 카테고리의 다른 글

222. Count Complete Tree Nodes  (0) 2023.01.27
257. Binary Tree Paths  (0) 2023.01.27
973. K Closest Points to Origin  (0) 2023.01.25
1046. Last Stone Weight  (0) 2023.01.25
703. Kth Largest Element in a Stream  (0) 2023.01.24