LeetCode之Search for a Range
2014-03-26 18:39
381 查看
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].
class Solution {
public:
vector<int> searchRange(int A[], int n, int target) {
vector<int> ivec;
int left=lower_bound(A,n,target);
if(left==n||A[left]!=target) {
ivec.push_back(-1);
ivec.push_back(-1);
return ivec;
}
ivec.push_back(left);
int right=upper_bound(A,n,target);
ivec.push_back(right-1);
return ivec;
}
//可插入target的第一个合适位置
int lower_bound(int A[],int n,int target){
int first=0,len=n,half;
int mid;
while(len>0){
half=len>>1;
mid=first+half;
if(A[mid]<target){
first=mid+1;
len=len-half-1;
}
else
len=half;
}
return first;
}
//可插入target的最后一个合适位置
int upper_bound(int A[],int n,int target){
int first=0,len=n,half;
int mid;
while(len>0){
half=len>>1;
mid=first+half;
if(A[mid]>target){
len=half;
}
else{
first=mid+1;
len=len-half-1;
}
}
return first;
}
};
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].
class Solution {
public:
vector<int> searchRange(int A[], int n, int target) {
vector<int> ivec;
int left=lower_bound(A,n,target);
if(left==n||A[left]!=target) {
ivec.push_back(-1);
ivec.push_back(-1);
return ivec;
}
ivec.push_back(left);
int right=upper_bound(A,n,target);
ivec.push_back(right-1);
return ivec;
}
//可插入target的第一个合适位置
int lower_bound(int A[],int n,int target){
int first=0,len=n,half;
int mid;
while(len>0){
half=len>>1;
mid=first+half;
if(A[mid]<target){
first=mid+1;
len=len-half-1;
}
else
len=half;
}
return first;
}
//可插入target的最后一个合适位置
int upper_bound(int A[],int n,int target){
int first=0,len=n,half;
int mid;
while(len>0){
half=len>>1;
mid=first+half;
if(A[mid]>target){
len=half;
}
else{
first=mid+1;
len=len-half-1;
}
}
return first;
}
};
相关文章推荐
- ecshop上传产品图片不显示的解决办法
- poj1753 位压缩+bfs
- 9.7 Region(部分)
- iOS 按钮拖动。
- Day3 - bind 显示或设置按键的组合
- 说说PHP是什么格式 要怎么打开
- 优酷土豆2012.9.12校园招聘笔试题
- Oracle 分区表
- 进程与I/O
- 自定义android的tab样式
- 关于oc中内存管理问题
- 比较 PHP集成开发工具(IDE)
- 找出数组中两个只出现一次的数字
- zoj 3626 Treasure Hunt I(树背包)
- 活用UML-软件设计高手(深圳 2014年4月26-27日)
- poj 3228 Gold Transportation
- Leetcode--Search in Rotated Sorted Array(旋转数组的查找)
- Tomcat 6.x 生成CSR
- 第三周作业——顺序查找和二分查找
- 对android的一些感想——2014-03-26