基于二分查找的两个数组求合集
吾十有五而志于学,三十而立,四十而不惑,五十而知天命,六十而耳顺,七十而从心所欲不逾矩
---- 论语
一个非常简单的例子,听到有人在说这个,就写下来玩玩。
package test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Demo2 { public static List<Integer> intersection(int[] arr1, int[] arr2){ List<Integer> list = new ArrayList<Integer>(); for(int i : arr1){ if(binarySearch(arr2, i)) list.add(i); } return list; } public static boolean binarySearch(int[] i, int j){ Arrays.sort(i); int low = 0; int high = i.length - 1; while(high >= low && low <= i.length - 1 && high <= i.length - 1){ int middle = low + ((high - low) >> 1); if(j == i[middle]){ return true; }else if(j > i[middle]){ low = middle + 1; }else{ high = middle - 1; } } return false; } public static void main(String[] args) { int[] arr1 = {1,2,4,5,6,7,11,34,56,55}; int[] arr2 = {6,7,11,4,35,9,0,44}; List<Integer> list = intersection(arr1, arr2); for(int i : list) System.out.print(i + ","); } }