AlgoFrames

K largest values

Warm-up · Write code · about 10 min

Given an array nums and a whole number k, return the k largest values of nums, largest first. Equal values count separately, so [4, 4, 1] with k = 2 gives [4, 4].

Use a min-heap that never holds more than k values. Do not sort the whole array.

Example 1

Input:

[[5,1,9,3,7],2]

Output:

[9,7]

9 and 7 are the two largest values.

Example 2

Input:

[[4,4,1],2]

Output:

[4,4]

Both copies of 4 count.

Constraints

  • 0 ≤ nums.length ≤ 10,000
  • 0 ≤ k ≤ nums.length
  • -10,000 ≤ nums[i] ≤ 10,000

Learn the idea first: Priority queues in practice: top-k, k-way merge, scheduling, a visual lesson.

More Priority queues in practice: top-k, k-way merge, scheduling problems