首页 > 代码库 > Search Insert Position (LeetCode)
Search Insert Position (LeetCode)
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 searchedkey
- 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 }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。