如何在Array中找到最常重复的数字?

时间:2014-11-29 01:23:09

标签: java arrays find

我知道有类似的问题。但这是一个技巧。我们假设我们有这个数组:

int[] list = {1, 2, 3, 1, 0, 0, 0, 5, 6, 1569, 1, 2, 3, 2, 1569, 3};

System.out.println("Most repeated value is: " + ???);    

/* Now As you can see 0's, 1's, 2's and 3's has the same frequency "3 times". In this case, 
   I need to print the smallest number which is the most frequently repeated. So that, 
   prompt should be 0 */

让它更容易理解:

// All the digits except 5 and 6 and 1569's rest of the values repeated 3 times. I have to
// print the smallest number which occurs most. 

如果您能在java中向我展示解决方案代码,我将非常感激。谢谢你检查。

2 个答案:

答案 0 :(得分:2)

    public static void main(String args[]) {
    int[] list = {1, 2, 3, 1, 0, 0, 0, 5, 6, 1569, 1, 2, 3, 2, 1569, 3};

    Map<Integer,Integer> map = new HashMap<Integer,Integer>();
    for (Integer nextInt : list) {
        Integer count = map.get(nextInt);
        if (count == null) {
            count = 1;
        } else {
            count = count + 1;
        }
        map.put(nextInt, count);
    }

    Integer mostRepeatedNumber = null;
    Integer mostRepeatedCount = null;
    Set<Integer>keys = map.keySet();
    for (Integer key : keys) {
        Integer count = map.get(key);
        if (mostRepeatedNumber == null) {
            mostRepeatedNumber = key;
            mostRepeatedCount = count;
        } else if (count > mostRepeatedCount) {
            mostRepeatedNumber = key;
            mostRepeatedCount = count;
        } else if (count == mostRepeatedCount && key < mostRepeatedNumber) {
            mostRepeatedNumber = key;
            mostRepeatedCount = count;
        }
    }

    System.out.println("Most repeated value is: " + mostRepeatedNumber);    

}

将提供以下输出......

Most repeated value is: 0

答案 1 :(得分:1)

我想我不必提O(n ^ 2)算法。

平均O(n)算法:

int maxCount = 0;
int maxKey = -1;
foreach element in array
{
  if(hashTable contains element)
  {
     increase the count;
     if (count > maxCount)
     {
        maxCount = count;
        maxKey = element
     }
     else if (count == maxCount && maxKey > element)
     {
        maxKey = element;
     }
  }
  else
  {
     insert into hash Table with count 1;
     if (1> maxCount)
     {
        maxCount = 1;
        maxKey = element
     }
  }
}

O(n)+ k算法: 同样的想法在数组中创建一个长度=最大值的数组,而不是hashTable,并做array[element]++;