(爪哇)我如何找到模式下使用一个简单的for循环(数组中最常见的值)? [英] (Java)How do I find the mode (most frequent value in an array) using a simple for loop?

查看:146
本文介绍了(爪哇)我如何找到模式下使用一个简单的for循环(数组中最常见的值)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何找到模式下使用一个简单的for循环(数组中最常见的值)?

要DaveRandom:这不是一个家庭作业的问题。学校目前尚未开庭。

在code有一个错误的输出编译。

下面是我:

 公共静态无效的模式(双[] ARR)
{
    双模式= ARR [0];    的for(int i = 1; I< arr.length;我++)
    {
        如果(==模式常用3 [I])
        {
            模式++;
        }     }
    返回模式;
}


解决方案

首先,我数组按订单进行排序,然后我算一个数字的出现。不包含HashMap只有for循环和if语句。

我的code:

 静态INT模式(INT [] N){
    INT T = 0;
    的for(int i = 0; I< n.length;我++){
        对于(INT J = 1; J< n.length-I; J ++){
            如果(N [J-1]将N [J]){
                T = N [J-1]。
                N [J-1] = N [J]。
                N [J] = T;
            }
        }
    }    INT模式= N [0];
    INT TEMP = 1;
    INT TEMP2 = 1;
    的for(int i = 1; I< n.length;我++){
        如果(N [I-1] == N [I]){
            临时++;
        }
        其他{
            温度= 1;
        }
        如果(临时> = TEMP2){
            模式= N [I]
            TEMP2 =温度;
        }
    }
    返回模式;
}

How do I find the mode (most frequent value in an array) using a simple for loop?

To DaveRandom: This is not a homework problem. School is currently not in session.

The code compiles with a wrong output.

Here is what I have:

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

解决方案

First I sort the array by order and then I count occurrences of one number. No hashmaps only for loop and if statements.

My code:

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屋!

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