zoukankan      html  css  js  c++  java
  • Leetcode Search Insert Position

    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;
    }
  • 相关阅读:
    VS2015, .NET 4.6, C# 6.0, F# 4.0等重量级产品正式上线
    Visual Studio 2015正式发布
    持续集成并不能消除 Bug,而是让它们非常容易发现和改正(转)
    如何用Excel直接查询Oracle中的数据(转)
    HTTP必知必会(转)
    二叉树的友好实现(转)
    TortoiseGit push失败原因小结(转)
    Android
    对JAVA Bean使用PropertyDescriptor反射调用JAVA方法
    关于MSHTML
  • 原文地址:https://www.cnblogs.com/xiongqiangcs/p/3763853.html
Copyright © 2011-2022 走看看