Find most common string in an array

前端 未结 6 1914
说谎
说谎 2020-12-24 07:42

I have this array, for example (the size is variable):

   x = [\"1.111\", \"1.122\", \"1.250\", \"1.111\"]

and I need to find the most comm

6条回答
  •  长情又很酷
    2020-12-24 08:37

    You could create a hashmap that stores the array items as keys with their values being the number of times that element appears in the array.

    Pseudo Code:

    ["1.111", "1.122", "1.250", "1.111"].each { |num|
      count=your_hash_map.get(num)
      if(item==nil)
        hashmap.put(num,1)
      else
        hashmap.put(num,count+1)
    }
    

    As already mentioned, sorting might be faster.

提交回复
热议问题