最快速度求两个数组的交集int[] a1,int[] a2
// 排序算法
public class SortClass {
static Map<Integer, Object> map = new ConcurrentHashMap<Integer, Object>();
public static void main(String[] args) throws IOException {
int[] array1 = new int[10000];
for (int i = 0; i < 10000; i++) {
array1[i]=i*i;
}
int[] array2 = new int[5000000];
for (int i = 0; i < 5000000; i++) {
array2[i]=i+i;
}
getRepeat(array1, array2);
getRepeatfor(array1, array2);
}
private static void wirteFile() throws IOException{
try {
FileOutputStream fos = new FileOutputStream (new File("d:\\a2.txt"),true ) ;
for (int i = 0; i < 1000; i++) {
int k = new Random().nextInt(100000);
fos.write((k+",").getBytes()) ;
}
fos.close ();
} catch (IOException e) {
e.printStackTrace();
}
}
//int数组求交集-采用hash碰撞方式
public static void getRepeat(int[] a1, int[] a2) {
int count=0;
long start = System.currentTimeMillis();
for (int i = 0; i < a1.length; i++) {
map.put(a1[i], a1[i]);
}
for (int j = 0; j < a2.length; j++) {
if (map.get(a2[j]) != null) {
count++;
}
}
System.out.println(count);
long end = System.currentTimeMillis();
System.out.println("耗时:"+(end -start)/1000+"s");
}
// int数组求交集-双重for循环
public static void getRepeatfor(int[] a1, int[] a2) {
int count=0;
long start = System.currentTimeMillis();
for (int i = 0; i < a1.length; i++) {
for (int j = 0; j < a2.length; j++) {
if(a2[j]==a1[i]){
count++;
}
}
}
System.out.println(count);
long end = System.currentTimeMillis();
System.out.println("耗时:"+(end -start)/1000+"s");
}
}
两个算法时间复杂度相差很大。