JAVA技巧(有序整数集合a和b的交集函数)
描述:
有两个有序整数集合A和b,写一个函数求它们的交集?
几种解决方案:
一:
导入Java . util . arrays;
公共类Test {
公共静态void main(String args[]){
int[]b = { 4,6,7,7,7,8,8,9,10,100,130,130,140,150 };
int[] a = {2,3,4,4,4,7,8,8,8,8,9,100,130,150,160 };
int[] c = intersect(a,b);
system . out . println(arrays . tostring(c));
}
public static int[]intersect(int[]a,int[]b){
if(a[0]> b[b . length-1]| | b[0]> a[a . length-1]){
return new int[0];
}
int[]intersection = new int[math . max(a . length,b . length)];
int offset = 0;
for(int i = 0,s = I;i < a .长度&& s < b .长度;i++){
while(a[I]> b[s]){
s++;
}
if(a[I]= = b[s]){
交集[offset++] = b[s++];
}
while(I <(a . length-1)& & a[I]= = a[I+1]){
i++;
}
}
if(intersection . length = = offset){
返回交集;
}
int[]duplicate = new int[offset];
System.arraycopy(交集,0,重复,0,偏移量);
返回重复项;
}
}
二:
导入Java . util . ArrayList;
公共类吉焦{
公共静态void main(String[]args){
//TODO自动生成的方法存根
int[] b = { 4,6,7,7,8,8,9,10,100,130,140,150 };
int[] a = { 2,3,4,4,4,7,8,8,8,9,100,130,150,160 };
ArrayList c = sect(a,b);
for(int I = 0;I < c . size();i++){
system . out . print(c . get(I)+",";
}
}
public static ArrayList Sect(int[]a,int[]b){
int k = 0;
int start posb = 0;
if(a[0]> b[b . length-1]| | b[0]> a[a . length-1]){
return new ArrayList();
}
ArrayList ArrayList = new ArrayList();
for(int I = 0;i < a .长度;i++){
for(int j = start posb;j < b .长度;j++){
if(a[I]= = b[j]){
ArrayList . add(k,a[I]);
k++;
start posb = j+1;
break;
}
}
}
return ArrayList;
}
}
三:
导入Java . util . hashset;
导入Java . util . iterator;
导入Java . util . set;
public class number cross {
public static void main(String[]args){
int a[]= { 1,3,4,5,6,7,499,199 };
int b[]= { 3299199,8,9499 };
Set list = new HashSet();
for(int I = 0;I list . add(a[I]);
}
for(int j = 0;j list . add(b[j]);
}
for(Iterator ITER = list . Iterator();ITER . has next();){
system . out . print(ITER . next()+" ");
}
}
}
0条评论