[Leetcode 23] 35 Search Insert Position

Problem:

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

 

Analysis:

An variant of binary search. Pay special attention what to return when there's no match

Time complexity is O(logn), space complexity is O(n)

 

Code:

 1 public class Solution {
 2     public int searchInsert(int[] A, int target) {
 3         // Start typing your Java solution below
 4         // DO NOT write main() function
 5         int lo = 0, hi = A.length-1;
 6         
 7         while (lo <= hi) {
 8             int mid = (lo + hi) / 2;
 9             
10             if (A[mid] == target) {
11                 return mid;
12             } else if (A[mid] < target) {
13                 lo = mid+1;
14             } else { //(A[mid] > target)
15                 hi = mid-1;
16             }
17         }
18         
19         return lo;
20     }
21 }
View Code

 

Attention:

The insertion place is lo no lo+1 if there is no match. The reason is (lo+hi)/2 will always make mid towards the lo, then when while loop exits (now lo=hi), both lo and hi points to the element that is just less then target element.

posted on 2013-05-19 09:01  freeneng  阅读(128)  评论(0编辑  收藏  举报

导航