码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode Search Insert Position

时间:2014-06-02 02:06:39      阅读:214      评论:0      收藏:0      [点我收藏+]

标签:c   style   class   blog   code   java   

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的效率竟然比直接二分搜索的效率好,现在一直迷惑

bubuko.com,布布扣
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 ;
}
bubuko.com,布布扣

附上lower_bound的源代码

bubuko.com,布布扣
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;
}
bubuko.com,布布扣

 利用最普通的二分搜索算法(耗时44ms)

bubuko.com,布布扣
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;
}
bubuko.com,布布扣

 

Leetcode Search Insert Position,布布扣,bubuko.com

Leetcode Search Insert Position

标签:c   style   class   blog   code   java   

原文地址:http://www.cnblogs.com/xiongqiangcs/p/3763853.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!