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数组不同,而两种方法性能不同,相差不大。