K Largest Elements with Quickselect
Problem statement
Given an integer array nums and an integer k, return the k largest occurrences in nonincreasing order. Preserve duplicate occurrences.
Your selection step should use in-place partitioning rather than maintaining a size-k heap. Sorting only the selected suffix for output order is allowed.
Function
kLargestQuickselect(nums: int[], k: int) → int[]Examples
Example 1
nums = [3,2,1,5,6,4]k = 2return = [6,5]Partitioning isolates 5 and 6, which are then ordered descending.
Example 2
nums = [4,1,4,2,4]k = 3return = [4,4,4]Duplicate occurrences are retained.
Example 3
nums = [-5,-1,-3]k = 0return = []Selecting zero values returns an empty array.
Constraints
0 <= nums.length <= 200000.-10^9 <= nums[i] <= 10^9.0 <= k <= nums.length.