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;
    }
  • 相关阅读:
    java第二次作业 数组和String类
    java第一次作业
    选择
    latex math
    sum的写法
    qt 4.8.5 vs 2012编译
    物联网笔记四:物联网网络及协议
    物联网学习笔记三:物联网网关协议比较:MQTT 和 Modbus
    物联网学习笔记二:物联网网关
    物联网学习笔记一:物联网入门的必备 7 大概念和技能
  • 原文地址:https://www.cnblogs.com/xiongqiangcs/p/3763853.html
Copyright © 2011-2022 走看看