LeetCode *** 34. Search for a Range
2016-04-17 23:13
399 查看
题目:
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
分析:
38.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].
分析:
38.1%,呵呵哒。。。这种二分的题我也能做成这样。。。。
代码:
class Solution { public: vector<int> searchRange(vector<int>& nums, int target) { if(nums.size()<1)return vector<int>{-1,-1}; int size=nums.size(); int low=0,high=size-1; vector<int> res; while(low<high){ int mid=(low+high)/2; if(nums[mid]==target){ low=mid-1,high=mid+1; while(low>=0&&nums[low]==target) if(nums[low]==target)low--; while(high<size&&nums[high]==target) if(nums[high]==target)high++; res.push_back(++low); res.push_back(--high); break; } if(nums[mid]>target){ high=mid; } else low=mid+1; } if(res.empty()){ if(nums[low]!=target)return vector<int>{-1,-1}; else { res.push_back(low); res.push_back(low); } } return res; } };
相关文章推荐
- ubuntu 设置 NAT 转发
- 课程练习二-1009连连看
- C++作业2
- ios开发之代理设计模式
- 使用WebMagic爬虫框架及javaEE SSH框架将数据保存到数据库(一)
- android studio “aapt” IOException error=2, No such file or directory"
- 学习进度第七周
- 自考结束了
- poj2488.特坑的一题
- 利用HTML5分片上传超大文件
- flash进行上传使用什么协议?
- Spring中配置数据源的4种形式
- 自考结束了
- 你是否是团队里面最默默付出的那个coder,却发现滔滔不绝的产品和设计是团队里的开心果(转)
- 都说「三观不正」,那么正确的三观是怎样的 [转]
- 笔记-->关系操作符 ==
- c++ 继承与权限
- 《第一行代码》第七章 读取系统联系人(一)
- Two Sum
- C++11 中的线程、锁和条件变量