首页 > 开发 > JAVA > 正文

有2个已经从小到大排序好的数组,要求只遍历一次,找出2个数组中共有的元素

2016-05-24 23:16:38  来源:慕课网
  package test;
  import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
  public class Test {
public static void main(String[] args) {
int[] a ={6,5,4,3,2};
int[] b ={8,5,3,2,1,0};
Set<Integer> setA=new HashSet<Integer>();
Set<Integer> setB=new HashSet<Integer>();
Set<Integer> setC=new HashSet<Integer>();
Set<Integer> setD=new HashSet<Integer>();
for(int i=0;i<(a.length>=b.length?a.length:b.length);i++){
if(i<a.length){
setA.add(a[i]);
setC.add(a[i]);
}
if(i<b.length){
setB.add(b[i]);
setD.add(b[i]);
}
}
if(a.length>=b.length){
setA.removeAll(setB);
setC.removeAll(setA);
Iterator<Integer> it =setC.iterator();
while(it.hasNext()){
Integer x=it.next();
System.out.println(x);
}
}else{
setB.removeAll(setA);
setD.removeAll(setB);
Iterator<Integer> it =setD.iterator();
while(it.hasNext()){
Integer x=it.next();
System.out.println(x);
}
}
}
}
Copyright©2013-2016abenmao All Rights Reserved 京ICP备13035258号