andrew9991 2016-05-03 12:47 采纳率: 100%
浏览 3153
已采纳

输出array中出现次数最多的数

用类似这种的方法 不用Map

int[] a = new int[10]{1,2,3,4,5,6,7,7,7,7};

public int getPopularElement(int[] a)
{
int count = 1, tempCount;
int popular = a[0];
int temp = 0;
for (int i = 0; i < (a.length - 1); i++)
{
temp = a[i];
tempCount = 0;
for (int j = 1; j < a.length; j++)
{
if (temp == a[j])
tempCount++;
}
if (tempCount > count)
{
popular = temp;
count = tempCount;
}
}
return popular;
}

我想让this.method = 那个出现次数最多的数字 如果所有数都只出现一次的话就this.method = -1
或者出现次数相同的话也是this.method = -1 。
我照着上面的方法写的没法判断每个数只出现一次的情况 还有出现次数相同的情况
求帮忙看看怎么写

public Long getMode() {

    Vector vector = cloned();
    long [] num = vector.getElements();


    // 要写的地方


    return this.method;
    }
  • 写回答

3条回答

  • havedream_one 2016-05-04 01:37
    关注
     public static int getPopularElement(int[] a)
    {
        if(a.length < 2){
            return a[0];
        }
        int[] t = new int[a.length];//记录每一个元素出现的次数
        int popular = -1;
        for (int i = 0; i < a.length; i++)
        {
            int temp = a[i];
            int count = 1;
            for (int j = 0; j < a.length; j++)
            {
                if(j == i){ 
                    continue;
                }
                if (temp == a[j])
                    count++;
            }
            t[i] = count;
        }
        //System.out.println(Arrays.toString(t));
        int first = t[0] > t[1] ? t[0] : t[1];
        int pos = t[0] > t[1] ? 0 : 1;
        int second = t[0] < t[1] ? t[0] : t[1];
        for(int i = 2; i < t.length; i++){
            if(t[i] >= first){
                first = t[i];
                pos = i;
                continue;
            }
            if(t[i] >= second){
                second = t[i];
            }
        }
        //System.out.println(first + "," + second);
        if(first == second ){
            return -1;
        }else{
            return a[pos];
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题