[java]代码库
下面这个方法 要求两个数组是已排序的
Java codepackage com.haojia.algorithm;
/**
* 求两个已排序的数组的交集
*
* @author July
*
*/
public class Intersect {
public static void go(int[] a, int[] b) {
int i = 0;
int j = 0;
while (i < a.length && j < b.length) {
if (a[i] < b[j]) {
i++;
} else if (a[i] > b[j]) {
j++;
} else {
System.out.print(a[i] + " ");
i++;
j++;
}
}
}
public static void main(String[] args) {
int[] a = { 1, 5, 8, 10, 14, 15, 17, 18, 20, 22, 24, 25, 28 };
int[] b = { 2, 4, 6, 8, 10, 12 };
go(a, b);
}
}
------解决方案--------------------
Java codeimport java.util.Arrays;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
public class SelectBag {
public static int find(int key,int[] N){
int lb=0;
int ub=N.length-1;
int in;
while(true){
in=(lb+ub)/2;
if(N[in]==key)
return in;
else if(lb>ub)
return -1;
else{
if(N[in]<key)
lb=in+1;
else
ub=in-1;
}
}
}
public static void main(String[] args){
int[] M=RandomIntArray(30);
int[] N=RandomIntArray(30);
System.out.println(Arrays.toString(M));
System.out.println(Arrays.toString(N));
Set<Integer> list=new HashSet<Integer>();
for(int m:M){
int getInt=find(m,N);
if(getInt!=-1)
list.add(N[getInt]);
}
System.out.println("两个数组中重复的元素有:"+list);
}
public static int[] RandomIntArray(int count){
int[] array=new int[count];
Random r=new Random();
for(int i=0;i<count;i++){
array[i]=r.nextInt(100);
}
Arrays.sort(array);
return array;
}
}
结果:
[1, 3, 8, 11, 12, 20, 22, 22, 31, 34, 37, 40, 41, 45, 48, 49, 50, 51, 57, 69, 72, 73, 84, 84, 85, 93, 93, 93, 98, 98]
[0, 4, 4, 9, 12, 16, 26, 26, 28, 32, 36, 41, 42, 44, 48, 48, 55, 56, 61, 65, 72, 72, 73, 75, 76, 78, 83, 84, 89, 94]
两个数组中重复的元素有:[84, 48, 41, 72, 12, 73]//源代码片段来自云代码http://yuncode.net