1、算法示例如下:(效率高的)
| 1 | public static int getUnion(int []a , int [] b) |
| 2 | { |
| 3 | int i=0,j=0,count=0; |
| 4 | while(i < a.length && j < b.length) |
| 5 | { |
| 6 | if(a[i] == b[j]) |
| 7 | { |
| 8 | i++; |
| 9 | j++; |
| 10 | count++; |
| 11 | } |
| 12 | else if(a[i] > b[j]) |
| 13 | { |
| 14 | j++; |
| 15 | } |
| 16 | else |
| 17 | { |
| 18 | i++; |
| 19 | } |
| 20 | } |
| 21 | return count; |
| 22 | } |
2、算法示例如下(内部搜索用的是二分搜索),效率不如第一个
| 1 | public static int getUnion(int[] arr1, int[] arr2) { |
| 2 | ExpandableIntArray eia = new ExpandableIntArray(); |
| 3 | int low = 0; |
| 4 | for (int i = 0; i < arr1.length; i++) { |
| 5 | int mid = 0; |
| 6 | int top = arr2.length - 1; |
| 7 | while (low <= top) { |
| 8 | mid = (low + top) / 2; |
| 9 | if (arr1[i] > arr2[mid]) { |
| 10 | low = mid + 1; |
| 11 | } else if (arr1[i] < arr2[mid]) { |
| 12 | top = mid - 1; |
| 13 | } else { |
| 14 | eia.add(arr1[i]); |
| 15 | break; |
| 16 | } |
| 17 | } |
| 18 | } |
| 19 | return eia.getSize(); |
| 20 | } |
注意:求交集之前要将数组排序,这样求交集的效率更高
3788

被折叠的 条评论
为什么被折叠?



