从n个整数中查找出现频率最高的所有整数

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.Set;

/**
 * 从n个整数中查找出现频率最高的所有整数(用java实现) 
 * 示例:5,5,8,5,3,5,3,3,3,1 
 * 中出现频率最高的整数是3和5
 * @author htcafe
 *
 */
public class MyAnswer {

    public static void main(String[] args) {
        
        long start = System.currentTimeMillis();
        
        int[] datas = getdata();
//        int[] datas = {1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3};
        Map<Integer, Integer> map = getMax(datas);
        int count = getCount(map.values());
        System.err.println(count);
        
        display(map, count);
        
        long end = System.currentTimeMillis();
        System.err.println("Complete the check in " + (end - start) + " ms!" +
                "\nThis test have " + datas.length + " datas!");
    }
    
    private static void display(Map<Integer, Integer> map, int count) {
        for(Iterator<Integer> it = map.keySet().iterator(); it.hasNext();) {
            int value = it.next();
            if(count == map.get(value))
                System.out.println(value);
        }
    }
    
    private static int getCount(Collection<Integer> set) {
        int temp = 0;
        for(Iterator<Integer> it = set.iterator(); it.hasNext();) {
            int value = it.next();
            if(value > temp)
                temp = value;
        }
        return temp;
    }
    
    private static Map<Integer, Integer> getMax(int[] datas) {
        Map<Integer, Integer> temp = new HashMap<Integer, Integer>();
        for(int i=0; i<datas.length; i++) {
            Integer t = temp.get(datas[i]);
            t = (t != null) ? t.intValue() : 0;
            temp.put(datas[i], t + 1);
        }
        return temp;
    }

    private static int[] getdata() {
        int NUMBER = 1000000;
        int[] arr = new int[NUMBER];
        Random ran = new Random(20090228);
        int sign = -1;
        for (int i = 0; i < NUMBER; i++) {
            sign *= -1;
            arr[i] = sign * ran.nextInt(NUMBER);
        }
        return arr;
    }
}
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值