日期:2014-05-20 浏览次数:20894 次
public static void main(String[] args){ int[] M={1,2,3,4,5,6,7,8,9,1,2,3}; int[] N={5,2,5,6,7,8,9}; Set<Integer> setM=new HashSet<Integer>(); for(int m:M) setM.add(m);//将数组M添加到setM中为了为了避免M中的重复元素 Set<Integer> setN=new HashSet<Integer>(); for(int n:N) setN.add(n);//将数组N添加到setN中为了为了避免M中的重复元素 HashBag bag=new HashBag();//HashBag是一个org.apache.commons.collections.bag包中的类,可以很简单的求出两个集合中的交集 bag.addAll(setM); bag.addAll(setN); System.out.println(bag); }
------解决方案--------------------
汗!刺激我呢!
那我想想看
------解决方案--------------------
下面这个方法 要求两个数组是已排序的
package 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); } }
------解决方案--------------------
import 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]