pq = [-x for x in arr[:k]] heapq.heapify(hp) for i inrange(k, len(arr)): if -pq[0] > arr[i]: heapq.heappop(pq) heapq.heappush(pq, -arr[i]) ans = [-x for x in pq] return ans
classSolution: defgetLeastNumbers(self, arr: List[int], k: int) -> List[int]: defquickSelect(arr,left,right,k): if k < 0: return []
if left <= right: i = left j = right key = arr[left] while i < j: while i < j and arr[j] > key: j -= 1 while i < j and arr[i] <= key: i += 1 if i < j: arr[i],arr[j] = arr[j],arr[i] arr[left],arr[j] = arr[j],arr[left]
classSolution: deffindKthLargest(self, nums: List[int], k: int) -> int: defquickSelect(arr,left,right,k): if k < 0: return []
if left <= right: i = left j = right key = arr[left] while i < j: while i < j and arr[j] > key: j -= 1 while i < j and arr[i] <= key: i += 1 if i < j: arr[i],arr[j] = arr[j],arr[i] arr[left],arr[j] = arr[j],arr[left]
.... if left <= right: i = left j = right a = random.randint(left, right) arr[left],arr[a] = arr[a],arr[left] key = arr[left] while i < j: while i < j and arr[j] > key: j -= 1 while i < j and arr[i] <= key: i += 1 if i < j: arr[i],arr[j] = arr[j],arr[i] arr[left],arr[j] = arr[j],arr[left] ...