【一天一道LeetCode】#34. Search for a Range
2016-05-01 11:30
176 查看
一天一道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].
(二)解题
/* 首先二分法查找目标值 然后沿着目标值左右延伸,依次找到相同值得左右边界 */ class Solution { public: vector<int> searchRange(vector<int>& nums, int target) { int i = 0; int j = nums.size()-1; int idx = -1; vector<int> ret; while(i <= j) { int mid = (i+j)/2; if(nums[mid] == target) { idx = mid; break; } else if(nums[mid]>target) { j = mid-1; } else if(nums[mid]<target) { i = mid+1; } } if(idx!=-1){ int k = idx; while(k>=0 && nums[k] == target) k--; int m = idx; while(m<nums.size()&&nums[m] == target) m++; ret.push_back(k+1); ret.push_back(m-1); } else{ ret.push_back(-1); ret.push_back(-1); } return ret; } };
相关文章推荐
- 用同文输入法,实现五笔双键布局
- 让一个平淡无奇的网站盈利你需要这五个主意
- iOS下使用FFMPEG
- [系统运维]进程的守护神 - Supervisor
- bat判断window服务是否存在
- [C++]实现--讨论关于实现中可能出现的问题
- C# winform中DataGridView最常用的知识点
- ArchLinux 升级导致的wifi故障
- 剑指offer----用两个队列实现一个栈(java代码)
- Windows10下80端口被PID为4的System占用导致Apache无法启动的分析
- HBase分布式安装配置图文详解
- 解决移动端a标签点击有边框问题
- J2EE环境搭建(二)安装Eclipse插件和第一个Eclipse项目
- SPFA队列模板
- HDU2037------贪心算法排序
- 计算地球上2点之间的距离
- 网站导航菜单 远择一个栏目跳转后,保持栏目为选中状态
- 寻找你的乘法人生—徐大伟_David
- Android开发系列二之窗口Activity的生命周期
- 7.3 命名空间