[leetcode] Search for a Range
2015-07-15 22:58
381 查看
From : https://leetcode.com/problems/search-for-a-range/
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
Hide Tags
Array Binary
Search
Hide Similar Problems
(M) Search Insert Position
Solution :
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].
Hide Tags
Array Binary
Search
Hide Similar Problems
(M) Search Insert Position
Solution :
class Solution { public: vector<int> searchRange(vector<int>& nums, int target) { int start=0, end=nums.size()-1; vector<int> ans(2); ans[0]=ans[1]=-1; while(start <= end) { int mid = (start+end)>>1; if(nums[mid] == target) { for(int i=mid; i>=start; i--) { if(nums[i] == target) { ans[0] = i; } } for(int i=mid; i<=end; i++) { if(nums[i] == target) { ans[1] = i; } } break; } if(nums[mid] > target) { end = mid-1; } else { start = mid+1; } } return ans; } };
相关文章推荐
- centos 重启网站服务器 httpd
- L3:==、java.lang.Object 类、toString()
- C语言函数之可变参数原理:va_start、va_arg及va_end
- Quartz2D
- 瀑布流接口的设计以及应用(四)
- 简化通知中心的使用
- Android -- Volley解析
- linux系统时间同步,硬件时钟和系统时间同步,时区的设置
- 二分查找法及其应用
- java的myeclipse,java页面修改默认的javadoc方法
- jquery 连接在div中显示
- android 游戏sdk嫁接方式
- ORACLE中创建表空间,创建表,修改表,授权
- 40岁应该学会的是面对和取舍
- java网络编程(1)
- Eclipse中设置ButterKnife进行注解式开发步骤
- Android网络框架-Volley(五) 使用Volley发送自定义Request
- 大数据技术之Flume研究摘要(一)
- 瀑布流接口的设计以及应用(三)
- 指针(一)