Start learning free

LESSON 273 OF 437 · HASH TABLE

Top K Frequent Elements in C++

Practice O(n)

Given a vector of integers nums and an integer k, return the k most frequent values in nums. You can return them in any order.

The frequency of a value is the number of times it appears in nums. The answer is guaranteed to be unique: every value in it appears more times than every value left out.

 

Example 1:

Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Explanation: 1 appears 3 times, 2 appears 2 times and 3 appears once. The 2 most frequent values are 1 and 2.

Example 2:

Input: nums = [1], k = 1
Output: [1]
Explanation: 1 is the only value, so it is also the most frequent one.

Example 3:

Input: nums = [4,-1,4,-1,7,4,-1,9], k = 2
Output: [4,-1]
Explanation: 4 and -1 both appear 3 times, 7 and 9 only once. [-1,4] is also a correct answer, since the order doesn't matter.

 

Constraints:

  • 1 <= nums.length <= 105
  • -104 <= nums[i] <= 104
  • k is between 1 and the number of different values in nums.
  • The answer is unique.

Note:

Your algorithm should run in O(n) time and use O(n) extra space, where n is the length of nums. Sorting the values by their frequency would already take O(n log n).

STEP 1 OF 12
    Ctrl + Enter to check

    Top K Frequent Elements in C++

    Keep going with C++About 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free