在数组中查找多个模式 [英] Finding Multiple Modes In An Array

查看:120
本文介绍了在数组中查找多个模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个查找数组中所有模式的java方法。我知道有一种简单的方法可以在数组中找到模式,但是当有多个单一模式时,我的方法只输出其中一种模式。我试图找到一种方法,但我不确定如何解决这个问题。任何人都可以帮我找出阵列中的所有模式吗?谢谢。



这里是我的代码,即使存在多种模式也只输出一种模式。

  public static int mode(int a []){
int maxValue = 0,maxCount = 0;
for(int i = 0; i< a.length; ++ i){
int count = 0;
for(int j = 0; j< a.length; ++ j){
if(a [j] == a [i])++ count;
}
if(count> maxCount){
maxCount = count;
maxValue = a [i];
}
}
返回maxValue;
}

好的,这是一个例子:
30
30
30
34
34
23



在这组数字中,只有一种模式,即30。 / p>

30
30
30
34
34
34
23



但是在这个集合中有两种模式,30和34.我希望我的代码能够输出它们两个,而它只打印一个。它只打印30个。

解决方案

以下代码将返回 Integer [] 包含模式。如果你需要 int [] ,你仍然需要将 Integer 实例转换为 int 手动。可能不是最有效的版本,但它与您的代码紧密匹配

  public static Integer [] mode(int a []) {
List< Integer> modes = new ArrayList< Integer>();
int maxCount = 0;
for(int i = 0; i< a.length; ++ i){
int count = 0;
for(int j = 0; j< a.length; ++ j){
if(a [j] == a [i])++ count;
}
if(count> maxCount){
maxCount = count;
modes.clear();
modes.add(a [i]);
}否则if(count == maxCount){
modes.add(a [i]);
}
}
返回modes.toArray(new Integer [modes.size()]);
}


I'm trying to write a java method which finds all the modes in an array. I know there is a simple method to find the mode in an array but when there are more than one single mode my method outputs only one of them. I've tried to find a way but am nit sure how to approach this problem. Can anyone help me out to find all the modes in the array? Thanks.

Yes here is my code which outputs only one mode even if multiple modes exist.

public static int mode(int a[]){
  int maxValue=0, maxCount=0;   
  for (int i = 0; i < a.length; ++i){
    int count = 0;
    for (int j = 0; j < a.length; ++j){
      if (a[j] == a[i]) ++count;
    }
    if (count > maxCount){
      maxCount = count;
      maxValue = a[i];
    }
  }
  return maxValue;
}

okay here's an example: 30 30 30 34 34 23

In this set of numbers there is only one mode, which is 30.

30 30 30 34 34 34 23

But in this set there are two modes, 30 and 34. I want my code to be able to output both of them, whereas it only prints one. It prints only 30.

解决方案

The following code will return you an Integer[] containing the modes. If you need an int[] instead, you still need to convert the Integer instances to ints manually. Probably not the most efficient version, but its matches closely to your code

public static Integer[] mode(int a[]){
  List<Integer> modes = new ArrayList<Integer>(  );
  int maxCount=0;   
  for (int i = 0; i < a.length; ++i){
    int count = 0;
    for (int j = 0; j < a.length; ++j){
      if (a[j] == a[i]) ++count;
    }
    if (count > maxCount){
      maxCount = count;
      modes.clear();
      modes.add( a[i] );
    } else if ( count == maxCount ){
      modes.add( a[i] );
    }
  }
  return modes.toArray( new Integer[modes.size()] );
}

这篇关于在数组中查找多个模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆