首先說一下二分法的應用場景面試
一個排好序的數組,而且不重複,要找到其中某個元素的索引,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