经典面试题,求两个集合的交集
方法一:
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 }
声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。
- 上一篇:没有了
- 下一篇:没有了