首页 > 代码库 > Search for a Range <leetcode>
Search for a Range <leetcode>
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]
.
算法:该算法来源于网络,用二分查找最左最右的位置,代码如下:
1 class Solution { 2 public: 3 vector<int> searchRange(int A[], int n, int target) { 4 int l=findPos(A,0,n-1,target,true); 5 int r=findPos(A,0,n-1,target,false); 6 vector<int> result; 7 result.push_back(l); 8 result.push_back(r); 9 return result;10 }11 int findPos(int a[],int beg,int end,int key,bool findLeft)12 {13 if(beg>end) return -1;14 int mid=(beg+end)/2;15 if(a[mid]==key)16 {17 int pos=findLeft?findPos(a,beg,mid-1,key,findLeft):findPos(a,mid+1,end,key,findLeft);18 return pos==-1?mid:pos;19 }20 else if(a[mid]<key)21 {22 findPos(a,mid+1,end,key,findLeft);23 }24 else if(a[mid]>key)25 {26 findPos(a,beg,mid-1,key,findLeft);27 }28 }29 };
Search for a Range <leetcode>
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。