標籤:style blog http java color 使用
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
Here are few examples.
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0
1 public class Solution {2 public int searchInsert(int[] A, int target) {3 int index = Arrays.binarySearch(A, target);4 if (index <0)5 index = (-index)-1;6 return index;7 }8 }
作者到期其實只需瞭解Java Arrays.binarySearch()就行。
binarySearch
public static int binarySearch(int[] a, int key)
-
Searches the specified array of ints for the specified value using the binary search algorithm. The array must be sorted (as by the
sort(int[]) method) prior to making this call. If it is not sorted, the results are undefined. If the array contains multiple elements with the specified value, there is no guarantee which one will be found.
該方法使用的是二分尋找法。輸入的數組必須是有序的,否則無法保證尋找效果。
-
-
Parameters:
-
a - the array to be searched
-
key - the value to be searched for
-
Returns:
-
index of the search key, if it is contained in the array; otherwise, (-(
insertion point) - 1). The
insertion point is defined as the point at which the key would be inserted into the array: the index of the first element greater than the key, or a.length if all elements in the array are less than the specified key. Note that this guarantees that the return value will be >= 0 if and only if the key is found.
-
如果目標在數組中則返回其在數組中的索引,否則返回目標在數組中的(-(
insertion point) - 1)。
-
jdk1.6的binarySearch源碼
-
1 private static int binarySearch0(int[] a, int fromIndex, int toIndex, 2 int key) { 3 int low = fromIndex; 4 int high = toIndex - 1; 5 6 while (low <= high) { 7 int mid = (low + high) >>> 1; 8 int midVal = a[mid]; 9 10 if (midVal < key)11 low = mid + 1;12 else if (midVal > key)13 high = mid - 1;14 else15 return mid; // key found16 }17 return -(low + 1); // key not found.18 }