Given a sorted array of integers, find the starting and ending position of a given target value.
Your algorithm‘s runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1,
-1]
.
For example,
Given [5,
7, 7, 8, 8, 10]
and target value 8,
return [3,
4]
.
思路:两次使用二分查找,分别找上限和下限
#include <iostream> #include <vector> #include <string> using namespace std; /* 在一个排好序的序列中找打某个值的第一个位置 和最后一个位置 */ pair<int,int> Findvalue(vector<int>& vec,int key) { pair<int,int> pos(-1,-1); int mid,begin = 0,end = vec.size(); mid = begin + (end-begin)/2; if(vec[mid] == key) { pos.first = mid; pos.second= mid; } int low = mid; int high = mid+1; // 找低地址 while(begin<= low) { mid = begin+(low-begin)/2; if(vec[mid] == key) { if(pos.first == -1 || (pos.first!=-1 && mid < pos.first)) pos.first = mid; low = mid-1; } else if(vec[mid] > key) low = mid-1; else begin = mid+1; } //找高地址 while(high <= end) { mid = high+ (end-high)/2; if(vec[mid] == key) { if(pos.first == -1 || (pos.first!=-1 && mid >pos.first)) pos.second =mid; high = mid+1; } else if(vec[mid] > key) end = mid-1; else high = mid+1; } return pos; } int main() { int array[]={5, 7, 7, 8, 8, 10}; vector<int> vec(array,array+sizeof(array)/sizeof(int)); pair<int,int> pos = Findvalue(vec,8); cout<<pos.first<<" "<<pos.second<<endl; return 0; }
原文地址:http://blog.csdn.net/yusiguyuan/article/details/44747545