Class: FindTopK

Inherits:
Object
  • Object
show all
Defined in:
lib/find_top_k.rb

Class Method Summary collapse

Class Method Details

.run(nums, k) ⇒ Object



2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/find_top_k.rb', line 2

def self.run(nums, k)
  h = {}
  a = []
  nums.each do |num|
      if h[num].nil?
          h[num] = 1
      else
          h[num] += 1
      end 
  end

  return nums if h.count == k
  return 'k cannot bigger than the number of unique elements in the array' if h.count < k

  h.each do |key, val|
      if a[val].nil?
          a[val] = [key]
      else
          a[val] << key
      end
  end
  a.compact.flatten[(-1-(k-1))..-1]
end