leetcode-Search for a Range
2015-11-09 23:08
274 查看
Difficulty: Medium
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
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 { int my_lowerBound(vector<int> &nums,int target){ int left =0; int right=nums.size()-1; while(left<=right){ int mid=left+(right-left)/2; if(nums[mid]==target){ if(mid==0||nums[mid-1]!=target) return mid; else right=mid-1; } else if(nums[mid]>target) right=mid-1; else left=mid+1; } return -1; } int my_upperBound(vector<int> &nums,int target){ int left =0; int size=nums.size(); int right=size-1; while(left<=right){ int mid=left+(right-left)/2; if(nums[mid]==target){ if(mid==size-1||nums[mid+1]!=target) return mid; else left=mid+1; } else if(nums[mid]>target) right=mid-1; else left=mid+1; } return -1; } public: vector<int> searchRange(vector<int>& nums, int target) { return {my_lowerBound(nums,target),my_upperBound(nums,target)}; } };
相关文章推荐
- [译]开始学习webpack
- HDU2037 今年暑假不AC 贪心算法
- 51nod 1097 拼成最小的数 (排序)
- 继承与接口动手动脑
- spring spel
- java查看工具jstack-windows
- JAVA获取WEB项目下的WEB-INF目录
- python学习笔记-day03 第四部分(函数和文件操作)
- 归纳事件的绑定
- [C++渐进]引用与指针
- 机器学习算法:逻辑回归
- Log4j多文件保存不同等级日志信息
- C/Cplusplus
- Linux文本处理三剑客之sed
- Android进阶之路——Android Studio使用与5.0新特性
- IOS 七种手势详解(动图+Demo下载)
- 创建/导入maven项目时 eclipse默认jdk版本配置
- java基础以及操作Excle
- 为什么V8引擎这么快?(转载)
- rownum与rowId