09-04-2015 Array

这是一道看似简单的题目。

BJP3 Exercise 7.5: mode

Status: not solved  You have solved this problem; good work!
Added by:Whitaker Brand on 2013/04/01
Language:Java
Popularity: 41 likes  icon Like

Write a method called mode that returns the most frequently occurring element of an array of integers. Assume that the array has at least one element and that every element in the array has a value between 0 and 100 inclusive. Break ties by choosing the lower value.

For example, if the array passed contains the values {27, 15, 15, 11, 27}, your method should return 15. (Hint: You may wish to look at the Tally program from earlier in this chapter to get an idea of how to solve this problem.)


我自己的答案,还对了,但是太多for loop了。

public static int mode(int[] arr) {
        int max = 0;
        int maxFreq = 0;

        Arrays.sort(arr);
        max = arr[arr.length-1];

        int[] count = new int[max + 1];

        for (int i = 0; i < arr.length; i++) {
            count[arr[i]]++;
        }

         for (int i = 0; i < count.length; i++) {
            if (count[i] > maxFreq) {
                maxFreq = count[i];
            }
        }
        
        for (int i = 0; i < count.length; i++) {
            if (count[i] == maxFreq) {
                return i;
            }
        }
        return -1;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值