Search Insert Position

本质上是lower_bound,注意其与upper_bound之间的差别

 int searchInsert(int A[], int n, int target)
      {
          //本质上实现lower_bound函数
          return lower_bound(A, A + n, target) - A;
      }

      template<typename ForwardIterator ,typename T>
      ForwardIterator lower_bound(ForwardIterator first, ForwardIterator last, T value)
      {
          while (first != last)
          {
              auto mid = next(first, distance(first, last) / 2);

              //对于upper_bound:if(value>=*mid)
              if (value > *mid)first = ++mid;
              else last = mid;
          }

          return first;

      }
View Code

 

posted @ 2016-07-16 10:10  牧马人夏峥  阅读(101)  评论(0编辑  收藏  举报