每日一题 性能比较

package com.mdt.day;
/*
 *一个整形数组 int[] a = {1,2,3,6,7,1,2........}
 *取出重复次数最多的元素
 */
 import java.util.Arrays;
import java.util.Date;

public class TestW {

    public static void main(String[] args) {
        int[] a = new int[40000000];
        for (int i = 0; i < a.length; i++) {
            a[i] = (int)(Math.random()*10)+1;
        }
        long now = System.currentTimeMillis();
        System.out.println("开始时间:"+ now);
         Arrays.sort(a);

         int count = 1;
         int maxCount = 1;
         String value = "";
         for (int j = 0; j < a.length - 1; j++) {
             if(a[j] == a[j+1]){
                 count++;
                 if(maxCount < count){
                     maxCount = count; 
                     value = a[j] + "";
                 }
             }else {
                 count = 1;
            }

         }
         System.out.println("重复值-----重复次数:" + value + "====" + maxCount);
         long now2 = System.currentTimeMillis();
         System.out.println("结束时间:"+ now2);
         long time = now2 -now;
         System.out.println("用时:" + time);
    }
}
package com.mdt.day;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/*
 *一个整形数组 int[] a = {1,2,3,6,7,1,2........}
 *取出重复次数最多的元素
 */
public class TestQ {

    public static void main(String[] args) {
        int[] a = new int[40000000];
        for (int i = 0; i < a.length; i++) {
            a[i] = (int)(Math.random()*10)+1;
        }
        long now = System.currentTimeMillis();
        System.out.println("开始时间:"+ now);
         Map map = new HashMap();
         for (int i = 0; i < a.length; i++) {
            int count = 1;
            if (map.containsKey(a[i])) {
                count = (int) map.get(a[i]);
                count++;
            }
            map.put(a[i], count);
        }
        System.out.println(map.toString());
        int maxNumber = max(map);
        System.out.println("重复最多的数字是:"+maxNumber);
        long now2 = System.currentTimeMillis();
        System.out.println("结束时间:"+ now2);
        long time = now2 -now;
        System.out.println("用时:" + time);
    }

    private static int max(Map map) {
        int temp = 1;
        int num = 1;
        for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) {
            int name = Integer.parseInt(iterator.next().toString());
            int count = Integer.parseInt(map.get(name).toString());
            if (temp <= count) {
                temp = count;
                num = name;
            }
        }
        return num;
    }

}

结论:随机生成的int数组不同,而两种方法性能不同,相差不大。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值