經典面試題,求兩個集合的交集

方法一:

          

private static Set<Integer> setMethod(int[] a,int[] b){
 2         Set<Integer> set = new HashSet<Integer>();
 3         Set<Integer> set2 = new HashSet<Integer>();
 4         for(int i=0; i<a.length; i++) {
 5             set.add(a[i]);
 6         }
 7         for(int j=0; j<b.length; j++) {
 8             if(!set.add(b[j]))
 9                 set2.add(b[j]);
10         }
11         return set2;
12     }

方法二
1   private static int[] intersect(int[] a, int[] b) {
 2         if (a[0] > b[b.length - 1] || b[0] > a[a.length - 1]) {
 3             return new int[0];
 4         }
 5         int[] intersection = new int[Math.max(a.length, b.length)];
 6         int offset = 0;
 7         for (int i = 0, s = i; i < a.length && s < b.length; i++) {
 8             while (a[i] > b[s]) {
 9                 s++;
10             }
11             if (a[i] == b[s]) {
12                 intersection[offset++] = b[s++];
13             }
14             while (i < (a.length - 1) && a[i] == a[i + 1]) {
15                 i++;
16             }
17         }
18         if (intersection.length == offset) {
19             return intersection;
20         }
21         int[] duplicate = new int[offset];
22         System.arraycopy(intersection, 0, duplicate, 0, offset);
23         return duplicate;
24     }


方法三

  
private static Set<Integer> forMethod(int[] a,int[] b){
 2         Set<Integer> set=new HashSet<Integer>();
 3         int i=0,j=0;
 4         while(i<a.length && j<b.length){
 5             if(a[i]<b[j])
 6                 i++;
 7             else if(a[i]>b[j])
 8                 j++;
 9             else{
10                 set.add(a[i]);
11                 i++;
12                 j++;
13             }
14         }
15         return set;
16     }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章