Skip to content

Instantly share code, notes, and snippets.

@codertcet111
Created October 23, 2024 16:49
Show Gist options
  • Save codertcet111/1c081dcd34d742c0d321cc98959da137 to your computer and use it in GitHub Desktop.
Save codertcet111/1c081dcd34d742c0d321cc98959da137 to your computer and use it in GitHub Desktop.
347. Leetcode top K frequent elements
=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
@codertcet111
Copy link
Author

Screenshot 2024-10-23 at 10 17 06 PM

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