[LeetCode] Search for a Range 二分搜索
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]
.
Array Binary Search
这道是变形的二分搜索,写的有点冗余,没有很好的合并在一起。
方法是先二分搜索到 其中一个target, 然后分别二分搜索边界。
#include <vector> #include <iostream> using namespace std; class Solution { public: vector<int> searchRange(int A[], int n, int target) { vector<int > ret(2,-1); if(n<1) return ret; int mid = helpFun(A,0,n-1,target); if(mid !=-1){ ret[0]=helpLeft(A,0,mid,target); ret[1]=helpRight(A,mid,n-1,target); } return ret; } int helpLeft(int *a,int lft, int rgt, int & tar) { if(a[lft]==tar) return lft; if(lft+1==rgt) return rgt; int mid = (lft+rgt)/2; if(a[mid]==tar) return helpLeft(a,lft,mid,tar); else return helpLeft(a,mid,rgt,tar); } int helpRight(int *a,int lft, int rgt, int & tar) { if(a[rgt]==tar) return rgt; if(lft+1==rgt) return lft; int mid = (lft+rgt)/2; if(a[mid]==tar) return helpRight(a,mid,rgt,tar); else return helpRight(a,lft,mid,tar); } int helpFun(int *a,int lft, int rgt, int & tar) { if(lft>rgt) return -1; if(lft == rgt){ if(tar==a[lft]) return lft; return -1; } if(lft +1 == rgt){ if(a[lft]==tar) return lft; if(a[rgt]==tar) return rgt; return -1; } int mid = (lft+rgt)/2; if(a[mid]==tar) return mid; if(a[mid]<tar) return helpFun(a,mid+1,rgt,tar); else return helpFun(a,lft,mid-1,tar); } }; int main() { int A[]={5, 7, 7, 8, 8, 10}; Solution sol; vector<int > ret = sol.searchRange(A,sizeof(A)/sizeof(int),8); cout<<ret[0]<<ret[1]<<endl; return 0; }
附件是一份集成的比较好的,思路是一样:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
vector<int> searchRange(int a[], int n, int target) { vector<int> result(2,-1); int left = INT_MAX; int right = INT_MIN; binSearch(a, 0 , n-1, n, target, left, right); if (left != INT_MAX && right != INT_MIN) { result[0] = left; result[1] = right; } return result; } void binSearch(int a[], int l ,int h, int n, int target, int& left, int& right) { if (l > h) return; int m = (l+h)/2; if (a[m] > target) { binSearch(a,l,m-1,n,target, left, right); } else if (a[m] < target) { binSearch(a,m+1,h,n,target, left, right); } else { if (m < left) { left = m; if (m > 0 && a[m-1] == target) { binSearch(a,l,m-1,n,target,left,m); } } if (m > right) { right = m; if (m < n-1 && a[m+1] == target) { binSearch(a,m+1,h,n,target,m,right); } } } }