求数组元素的并集
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /** 2 * 3 * @author hanxin 4 * 标题:实现C=A并B 5 */ 6 7 public class Union 8 { 9 public static int[] A={3,5,20,8,11,2,6};//数组A 10 public static int[] B={2,6,8,9,11,15,5,20,44};//数组B 11 public static ArrayList<Integer> union(int[] A,int [] B) 12 { 13 ArrayList<Integer> C=new ArrayList<Integer>(); 14 int k=0; 15 for(int t=0;t<A.length;t++) 16 { 17 C.add(A[t]);//先将数组A位置t上的元素的值赋给数组my对应位置t上的元素 18 } 19 int i=0; 20 while(i<B.length) 21 { 22 23 for(int j=0;j<A.length;j++) 24 { 25 if(A[j]==B[i])//问题出在这,比较了就添加,可是实际是要比较完一次循环才添加 26 { 27 i++;//如果相同,则直接跳过该次循环 【这句不能少】 28 break; 29 } 30 else//如果两元素不相同 31 { 32 if(j==A.length-1)//且比较到此次循环的最后一个元素也不存在相同【即证明全部已经比较过】 33 { 34 C.add(B[i]); 35 k++; 36 i++; 37 } 38 } 39 } 40 } 41 42 return C; 43 } 44 public static void main(String[] args) { 45 // TODO Auto-generated method stub 46 ArrayList<Integer> C=union(A, B); 47 for(int i=0;i<C.size();i++) 48 { 49 System.out.println(C.get(i)); 50 } 51 } 52 }
如果有问题请指出,或者有更好的实现思路等希望能分享。
小小程序员--一直很安静的我。