Leetcode Search Insert Position

OpenSoucre發表於2014-06-01

Search Insert Position

 Total Accepted: 15484 Total Submissions: 44816

 

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,2,2,2,3]),如果永許用stl的話非常簡單(耗時16ms)

int searchInsert(int A[], int n, int target) {
   return distance(A,lower_bound(A,A+n,target));
}

下面自己仿照stl中lower_bound實現二分搜尋演算法(耗時44ms),有個不能理解的地方就是,用呼叫stl的效率竟然比直接二分搜尋的效率好,現在一直迷惑

int searchInsert(int A[], int n, int target){
    int* first = A, *second = A+n;
    while( n > 0){
        int half = n >> 1;
        int* middle = first + half;
        if(*middle < target ){
            first = ++middle;
            n -= half+1;
        }else{
            n = half;
        }
    }
    return first - A ;
}

附上lower_bound的原始碼

template <class ForwardIterator, class T>
  ForwardIterator lower_bound (ForwardIterator first, ForwardIterator last, const T& val)
{
  ForwardIterator it;
  iterator_traits<ForwardIterator>::difference_type count, step;
  count = distance(first,last);
  while (count>0)
  {
    it = first; step=count/2; advance (it,step);
    if (*it<val) {                 // or: if (comp(*it,val)), for version (2)
      first=++it;
      count-=step+1;
    }
    else count=step;
  }
  return first;
}

 利用最普通的二分搜尋演算法(耗時44ms)

int searchInsert3(int A[], int n, int target){
    int left = 0, right = n-1;
    while(left <= right){
        int middle = (right+left) >> 1;
        if(A[middle]<target) left = ++middle;
        else right = --middle;
    }
    return left;
}

 

相關文章