arrays - 在未排序的数组中查找最大出现整数 (Mode)

标签 arrays

如何在未排序的整数数组中找到出现最大次数(众数)的整数?

我能想到的一种O(nlogn) 方法是排序。还有其他更好的方法吗?

最佳答案

以下是您将要做的事情的基本概述:

  1. 首先对数组进行排序 - O(n logn) incase of merge sort
  2. 声明 Count=1, Max_Count=1, Max_Value=arr[0]
  3. 从索引 1 开始遍历数组
  4. 将每个元素与前一个元素进行比较。更新计数,Max_Count 如果它们相等,否则将计数重置回 1
  5. 返回 Max_Count, Max_value
Time Complexity  : O(n logn)+ O(n)
Space Complexity : InPlace , no hash table or hash map is required.

Here is the code:

public void Max_Occurrence(int[] arr)
{
    int count=1;
    int max_count =1;
    int max_value = arr[0];
    for(int i=1; i<arr.length ; i++)
    {
        if(arr[i-1] == arr[i])
        {
            count++;
            if(max_count<count)
            {
                max_count = count;
                max_value = arr[i];
            }
        }
        else
        {
            count = 1;//changing from count++. As per the steps mentioned above it should be reset to count = 1. Suggested by an anonymous user
        }
    }

    System.out.println("Result:"+max_value+" has occured "+max_count+"of times");
}

关于arrays - 在未排序的数组中查找最大出现整数 (Mode),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2455734/

相关文章:

Java:具有两个变量的二维数组

c++ - 如何从 BYTE* 读取一些字节

ruby - 如何从数组创建散列

java - 如何使用java将字符串数组或整数值从一个类传递到另一个类?

javascript - 如何过滤包含具有多个字符串值的键的数组?

c - 如何仅使用一个函数扫描任何二维数组?

javascript - 如何使用 javascript 在数组中查找顺序更改的内容?

ios - 使用 SpriteKit 传递多个数组 - UIColor 和 String

javascript - 根据对象中字段的存在对数组进行排序

java - 为什么 Stack 使用基于 1 的索引而不是像 Java 中的数组那样使用基于 0 的索引?