简体   繁体   English

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

[英]How to find the most frequently repeated number in Array?

I know there are similar questions like this one. 我知道有类似这样的问题。 But here's a trick. 但这是一个技巧。 Let's assume that we have this array: 我们假设我们有这个数组:

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 */

To make it more understandable: 为了使它更容易理解:

// 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. 

If you could show me a solution code wise in java I would very appreciate it. 如果您能在java中向我展示解决方案代码,我将非常感激。 Thanks for checking. 谢谢你检查。

    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);    

}

will give the following output ... 将给出以下输出......

Most repeated value is: 0

I guess I don't have to mention the O(n^2) algorithm. 我想我不必提O(n ^ 2)算法。

The average O(n) algorithm: 平均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 algorithm: same idea make an array with length = max value in the array instead of hashTable, and do array[element]++; O(n)+ k算法:同样的想法在数组中创建一个长度=最大值的数组而不是hashTable,并且做array[element]++;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM