二分查找是我们经常会遇到的算法,思路清晰,代码简洁。二分查找要求序列有序,且支持随机存取,一般情况下我们讨论的序列不存在相同元素,则二分查找可以很熟练的表示如下:
int binsearch(int A[], int n, int target) { int left=0,right=n-1,res=-1; while(left<=right) { int mid = left+((right-left)>>1); if(A[mid]<target) left = mid+1; else if(A[mid]>target) right = mid-1; else { return mid; } } return -1; }但是当我们对有序序列不做要求时,即可能出现相同的元素的情况下,二分查找就回出现一些扩展的问题,比如:
int searchLowerBound(int A[], int n, int target) { int left=0,right=n-1,res=-1; while(left<=right) { int mid = left+((right-left)>>1); if(A[mid]<target) left = mid+1; else if(A[mid]>target) right = mid-1; else { res = mid; right = mid-1; } } return res; }对于(2),同理可得:
int searchHigherBound(int A[], int n, int target) { int left=0,right=n-1,res=-1; while(left<=right) { int mid = left+((right-left)>>1); if(A[mid]<target) left = mid+1; else if(A[mid]>target) right = mid-1; else { res = mid; left = mid+1; } } return res; }对于(3),使得key=key-1,则转换成问题(2),对于(4),使得key=key+1,则转换成问题(1)。
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].
这个题就是要求出最小的value的下标和最大的value的下标,所以代码易得:
class Solution { public: int searchLowerBound(int A[], int n, int target) { int left=0,right=n-1,res=-1; while(left<=right) { int mid = left+((right-left)>>1); if(A[mid]<target) left = mid+1; else if(A[mid]>target) right = mid-1; else { res = mid; right = mid-1; } } return res; } int searchHigherBound(int A[], int n, int target) { int left=0,right=n-1,res=-1; while(left<=right) { int mid = left+((right-left)>>1); if(A[mid]<target) left = mid+1; else if(A[mid]>target) right = mid-1; else { res = mid; left = mid+1; } } return res; } vector<int> searchRange(int A[], int n, int target) { vector<int> res; res.push_back(searchLowerBound(A,n,target)); res.push_back(searchHigherBound(A,n,target)); return res; } };
原文地址:http://blog.csdn.net/majing19921103/article/details/44808663