使用简单的for循环查找模式(数组中最常见的值)? [英] Find the mode (most frequent value in an array) using a simple for loop?
本文介绍了使用简单的for循环查找模式(数组中最常见的值)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用简单的for循环找到模式(数组中最常见的值)?
How do I find the mode (most frequent value in an array) using a simple for loop?
代码编译输出错误。
这就是我所拥有的:
public static void mode(double [] arr)
{
double mode=arr[0];
for(int i = 1; i<arr.length; i++)
{
if(mode==arr[i])
{
mode++;
}
}
return mode;
}
推荐答案
首先我按数组排序然后我计算一个数字的出现次数。没有用于循环和if语句的hashmap。
First I sort the array by order and then I count occurrences of one number. No hashmaps only for loop and if statements.
我的代码:
static int Mode(int[] n){
int t = 0;
for(int i=0; i<n.length; i++){
for(int j=1; j<n.length-i; j++){
if(n[j-1] > n[j]){
t = n[j-1];
n[j-1] = n[j];
n[j] = t;
}
}
}
int mode = n[0];
int temp = 1;
int temp2 = 1;
for(int i=1;i<n.length;i++){
if(n[i-1] == n[i]){
temp++;
}
else {
temp = 1;
}
if(temp >= temp2){
mode = n[i];
temp2 = temp;
}
}
return mode;
}
这篇关于使用简单的for循环查找模式(数组中最常见的值)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文