标签:c style class blog code java
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; }
Leetcode Search Insert Position,布布扣,bubuko.com
Leetcode Search Insert Position
标签:c style class blog code java
原文地址:http://www.cnblogs.com/xiongqiangcs/p/3763853.html