LeetCode 34 - Search for a Range
2016-03-01 15:24
344 查看
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
[-1, -1].
For example,
Given
[5, 7, 7, 8, 8, 10]and target value 8,
return
[3, 4].
My Code
class Solution { public: vector<int> searchRange(vector<int>& nums, int target) { int size = nums.size(); int left_idx = 0; int right_idx = size - 1; int mid_idx; vector<int> range(2, -1); // Find start while (left_idx <= right_idx) { mid_idx = (left_idx + right_idx) / 2; if (nums[mid_idx] == target) { if (mid_idx == 0 || nums[mid_idx-1] < target) { range[0] = mid_idx; break; } else right_idx = mid_idx - 1; } else if (nums[mid_idx] < target) left_idx = mid_idx + 1; else right_idx = mid_idx - 1; } // Find end if (range[0] != -1) { left_idx = range[0] + 1; right_idx = size - 1; while (left_idx <= right_idx) { mid_idx = (left_idx + right_idx) / 2; if (nums[mid_idx] == target) { if (mid_idx == size - 1 || nums[mid_idx+1] > target) { range[1] = mid_idx; break; } else left_idx = mid_idx + 1; } else if (nums[mid_idx] < target) left_idx = mid_idx + 1; else right_idx = mid_idx - 1; } } if (range[1] == -1) range[1] = range[0]; return range; } };Runtime: 12 ms
相关文章推荐
- 客户端中消息的轮换出现 TextSwitcher
- android 开发技巧(9)--为文本添加发亮的效果
- Android照片墙完整版,完美结合LruCache和DiskLruCache
- linux C++ 获取当前时间,以标准时间“年-月-日 时:分:秒”的形式输出,且秒后边跟小数精确到毫秒
- JavaScript 获取对象属性和方法
- sed替换变量
- scala 隐式转换参数
- mysql用户权限管理
- 轻量级asp.net ajax解决方案详解
- 解析WordPress中控制用户登陆和判断用户登陆的PHP函数
- Cocos2d-x3.0模版容器详解之三:cocos2d::Value
- 构建基于微服务的云平台-技术架构选型
- scala object隐式对象
- Lua学习笔记-string库的使用
- iOS WebView与h5
- JAVA分布式事务原理及应用(转)
- 【duilib进阶】自定义控件响应指定命令
- iOS 证书
- Python Requests-学习笔记(8)-重定向与请求历史
- CCProcxy代理服务器的配置使用