Created
October 23, 2024 16:49
-
-
Save codertcet111/1c081dcd34d742c0d321cc98959da137 to your computer and use it in GitHub Desktop.
347. Leetcode top K frequent elements
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
=begin | |
Leetcode 347. Top K Frequent Elements | |
Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order. | |
Example 1: | |
Input: nums = [1,1,1,2,2,3], k = 2 | |
Output: [1,2] | |
Example 2: | |
Input: nums = [1], k = 1 | |
Output: [1] | |
=end | |
def top_k_frequent(nums, k) | |
fre ={} | |
nums.each {|el| fre[el] = fre[el] ? fre[el] + 1 : 1} | |
fre.sort_by{|k,v| -v }.map{|x| x[0]}[0...k] | |
end |
Author
codertcet111
commented
Oct 23, 2024

Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment