Search Insert Position (LeetCode)

來源:互聯網
上載者:User

標籤: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     }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.