LeetCode 之 Search for a Range
2016-05-09 13:22
525 查看
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
有序数组中的查找,使用二分查找,由于是要查重复元素的上下边界,所以要不止一次的二分查找,根据网上一篇博文的思路是用两次二分查找分别找到左右边界,需要注意到:在寻找左边界时,low要一直寻找target元素,在寻找右边界时,low遇到target要向右移动,直到不等于target。代码如下:
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].
有序数组中的查找,使用二分查找,由于是要查重复元素的上下边界,所以要不止一次的二分查找,根据网上一篇博文的思路是用两次二分查找分别找到左右边界,需要注意到:在寻找左边界时,low要一直寻找target元素,在寻找右边界时,low遇到target要向右移动,直到不等于target。代码如下:
class Solution { public: vector<int> searchRange(vector<int>& nums, int target) { vector<int> ans={-1,-1}; int length=nums.size(); if(length==0) return ans; int llow=0,lhigh=length-1; while(llow<=lhigh){ int mid=(llow+lhigh)/2; if(nums[mid]<target) llow=mid+1; else lhigh=mid-1; } int rlow=0,rhigh=length-1; while(rlow<=rhigh){ int mid=(rlow+rhigh)/2; if(nums[mid]<=target) rlow=mid+1; else rhigh=mid-1; } if(llow<=rhigh){ ans[0]=llow; ans[1]=rhigh; } return ans; } };
相关文章推荐
- 160509、Java过滤器与SpringMVC拦截器之间的关系与区别
- C#脱离Halcon编程开发环境使用方法
- typedef语句
- 个人博客网站的经营之道
- 排序算法
- POJ1005
- LeetCode 278. First Bad Version
- C 运算符优先级列表
- Palindromic Squares
- mysql char、varchar
- Dremel和Hadoop
- C语言————常量 、变量、 表达式、 语句详谈
- Yii2.0 RESTful Web服务(4)
- 一站式远程页面调试工具spy-debugger 2.0,已支持HTTPS
- vagrant搭建lamp开发环境
- Android_Studio 及SDK下载
- Hadoop笔记2016-05-09
- JavaScript的获取非行间样式
- java基本排序算法总结 (二)——快速排序法
- HashMap与HashTable的区别?