반응형
Problem
Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
Example 1:
Input: [3,2,1,5,6,4]
and k = 2
Output: 5
Example 2:
Input: [3,2,3,1,2,4,5,5,6]
and k = 4
Output: 4
Note:
You may assume k is always valid, 1 ≤ k ≤ array's length.
Solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | import heapq class Solution: def findKthLargest(self, nums: 'List[int]', k: 'int') -> 'int': # Time complexity : O(N*logK) # Space complexity : O(K) heap = [] for i in nums : heapq.heappush(heap, i) if len(heap) > k : heapq.heappop(heap) return heapq.heappop(heap) def findKthLargest(self, nums: 'List[int]', k: 'int') -> 'int': # Time complexity : O(N) # Space complexity : O(1) def partition(l, r, i): start = l pivot = nums[i] nums[i], nums[start] = nums[start], nums[i] l += 1 while l <= r : while l<=r and nums[l] <= pivot : l += 1 while l<=r and nums[r] > pivot : r -= 1 if l < r : nums[l], nums[r] = nums[r], nums[l] l += 1 r -= 1 nums[r], nums[start] = nums[start], nums[r] return r def select(l, r, k_smallest): if l == r : return nums[l] i = random.randint(l, r) i = partition(l, r, i) if k_smallest == i : return nums[i] elif k_smallest > i : return select(i+1, r, k_smallest) else : return select(l, i-1, k_smallest) return select(0, len(nums)-1, len(nums)-k) | cs |
반응형
'0 > algorithm' 카테고리의 다른 글
Topological Sorting (위상 정렬) (0) | 2019.03.10 |
---|---|
How to approach most of DP problems (House Robber) (0) | 2019.02.14 |
회전된 배열에서의 검색 (이진 탐색) (0) | 2019.02.10 |
이진 트리 균형 확인 (0) | 2019.02.07 |
Contains Duplicate3 (in Python) (0) | 2019.02.02 |