LeetCode:Search for a Range
2015-10-28 12:57
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
思路:
1、利用二分查找法找到目标值;
2、从中间值向左找,找到与目标值相等的第一个值得下标,同理,找到右边最后一个相同值得下标;
例如: 3,4,5,6,6,6,6,6,6,7,8,9,左下标为3,右下标为8.
3、返回两个下标。
代码:
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].
思路:
1、利用二分查找法找到目标值;
2、从中间值向左找,找到与目标值相等的第一个值得下标,同理,找到右边最后一个相同值得下标;
例如: 3,4,5,6,6,6,6,6,6,7,8,9,左下标为3,右下标为8.
3、返回两个下标。
代码:
class Solution { public: int searchtarget(vector<int>& nums, int start,int end,int target) { int mid; if(start > end) return -1; else { mid = start + (end - start) / 2; if(nums[mid] == target) { return mid; } else if(nums[mid] > target) { return searchtarget(nums,start,mid - 1,target); } else { return searchtarget(nums,mid + 1,end,target); } } } vector<int> searchRange(vector<int>& nums, int target) { vector<int> result; int n = nums.size(); int index = searchtarget(nums,0,n-1,target); if(index == -1) { result.push_back(-1); result.push_back(-1); return result; } else { int ls = index; while(ls>0 && nums[index] == nums[ls-1]) <span style="white-space:pre"> </span>ls--; int rs = index; while(rs<n-1 && nums[index] == nums[rs+1]) <span style="white-space:pre"> </span>rs++; result.clear(); result.push_back(ls); result.push_back(rs); } return result; } };
相关文章推荐
- LM(Levenberg-Marquard)算法的实现
- webWMS开发过程记录(二)- WMS是什么
- 相互激励
- hihoCoder #1197 Give My Text Back
- block的一点知识
- myeclipse集成maven问题解决
- SVN使用小结
- /proc/mtd 各参数的含义 -- linux内核
- 爱你.一万年>>数据库基础
- cocos2d-x移植到android
- java.lang.UnsupportedOperationException: addView(View, LayoutParams) is not supported in AdapterView
- [备忘]适配Android M 将HttpClient替换为HttpUrlConnection相关资料
- Unity5中优化VR 应用的12个技巧
- Android studio 1.4 学习笔记
- activity 四种启动模式详解
- Java 反射专题
- shell编程获取文件名以及文件后缀名.
- 电灯节电小知识的方法大全(转载)
- vsftpd server
- define宏定义细节及uCOS中宏定义技巧