首先说一下二分法的应用场景面试
一个排好序的数组,而且不重复,要找到其中某个元素的索引,for循环效率太慢,应采用二分法数组
第一个实现,是我在美团面试时写的,以下递归
public static void main(String[] args) { int[] a = {0,1,2,3,4,5,6,7,8}; System.out.println(getIndex(a, 0, a.length - 1, 9)); } /** * * @param a 要查找的数组 * @param low 查找范围的起始索引 * @param high 查找范围的结束索引 * @param num 要找的数字 * @return 要找数字的索引 */ public static int getIndex(int[] a,int low,int high,int num){ System.out.println("low:" + low + "-high:" + high); if(low<=high){ if(a[(low + high)/2] > num){ return getIndex(a,low,(low + high)/2 -1,num); }else if(a[(low + high)/2] < num){ return getIndex(a,(low + high)/2 +1,high,num); }else{ return (low + high)/2; } } return -1; }
第二种实现,是后来在网上找到的索引
public static int search(int[] arr, int key) { int start = 0; int end = arr.length - 1; while (start <= end) { int middle = (start + end) / 2; if (key < arr[middle]) { end = middle - 1; } else if (key > arr[middle]) { start = middle + 1; } else { return middle; } } return -1; }
意思都差很少,我是用的递归,网上找的用的是循环,不过多掌握一种方法,老是好的get