Find the element with highest occurrences in an array [java]

后端 未结 11 1500
后悔当初
后悔当初 2021-01-18 02:36

I have to find the element with highest occurrences in a double array. I did it like this:

int max = 0;
for (int i = 0; i < array.length; i++) {
       in         


        
11条回答
  •  一生所求
    2021-01-18 03:27

    Here is Ruby SOlution:

    def maxOccurence(arr)
      m_hash = arr.group_by(&:itself).transform_values(&:count)
      elem = 0, elem_count = 0
      m_hash.each do |k, v|
        if v > elem_count
            elem = k
            elem_count = v
        end
      end
      "#{elem} occured #{elem_count} times"
    end
    
    p maxOccurence(["1", "1","1","1","1","1","5","5","12","12","12","12","12","12","12","12","12","12","8"])
    

    output:

    "12 occured 10 times"
    

提交回复
热议问题