标签: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()就行。
public static int binarySearch(int[] a, int key)
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.
该方法使用的是二分查找法。输入的数组必须是有序的,否则无法保证查找效果。
a
- the array to be searchedkey
- the value to be searched for1 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 else 15 return mid; // key found 16 } 17 return -(low + 1); // key not found. 18 }
Search Insert Position (LeetCode),布布扣,bubuko.com
Search Insert Position (LeetCode)
标签:style blog http java color 使用
原文地址:http://www.cnblogs.com/weilq/p/3811403.html