Search for a Range
2015-07-24 10:19
176 查看
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
For example,
Given
return
Analyse: Binary search.
Runtime: 12ms.
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].
Analyse: Binary search.
Runtime: 12ms.
class Solution { public: vector<int> searchRange(vector<int>& nums, int target) { vector<int> result; if(nums.size() == 0) return result; int left = findLeft(nums, target); int right = findRight(nums, target); result.push_back(left); result.push_back(right); return result; } int findLeft(vector<int> &nums, int target){ int low = 0, high = nums.size() - 1; while(low <= high){ int mid = (low + high) / 2; if(nums[mid] < target) low = mid + 1; else high = mid - 1; } if(nums[low] != target) return -1; else return low; } int findRight(vector<int> &nums, int target){ int low = 0, high = nums.size() - 1; while(low <= high){ int mid = (low + high) / 2; if(nums[mid] > target) high = mid - 1; else low = mid + 1; } if(nums[high] != target) return -1; else return high; } };
相关文章推荐
- sql 分页存储过程
- dialog弹出,点击back按键无法返回问题解决
- HDU 5308 I Wanna Become A 24-Point Master(2015多校第二场)
- 五种基于RGB色彩空间统计的皮肤检测算法
- 五种基于RGB色彩空间统计的皮肤检测算法
- 实习16天
- 五种基于RGB色彩空间统计的皮肤检测算法
- HDU 1710 二叉树遍历
- Spring+iBatis+Atomikos实现JTA事务
- iOS appdelegate 中将自定义的视图作为启动视图
- 五种基于RGB色彩空间统计的皮肤检测算法 分类: 视频图像处理 2015-07-24 10:18 48人阅读 评论(0) 收藏
- java中全排列的生成算法汇总
- 图像处理------图像梯度效果
- 图像处理------图像梯度效果
- 超详细介绍 图像处理(卷积)
- 论文参考文献
- 图像处理------图像梯度效果
- html中<li></li>中使用<br>和<li></li>外面使用<br>
- 有没有一个命令把linux下的分区的各个卷标都对应着显示出来?
- js中运算符的优先级