Question
Given a target number and an integer array A sorted in ascending order, find the index i in A such that A[i] is closest to the given target. Return -1 if there is no element in the array.
Explanation
被面到了这道题!先排个序,接着二分查找。注意最后选择start还是选择end。
Code
12345678910111213141516171819202122public void search(int[] array, int k) { Arrays.sort(array); int start = 0; int end = arrays.length; while(start+1 < end) { int mid = start + (end - start)/2; if (array[mid] == k) return mid; if (array[mid] > k) { start = mid; } else { end = mid; } } if (k <= array[start]) return start; if (k >= array[end]) return end; if (k - array[start] > array[end] - k) { return end; } else { return start; }}