[LeetCode] Search for a Range
2015-08-15 16:23
531 查看
The idea is to search for the left and right boundaries of target via two binary searches. Well, some tricks may be needed. Take a look at this link :-)
The code is rewritten as follows.
The code is rewritten as follows.
class Solution { public: vector<int> searchRange(vector<int>& nums, int target) { int l = left(nums, target); if (l == -1) return {-1, -1}; return {l, right(nums, target)}; } private: int left(vector<int>& nums, int target) { int n = nums.size(), l = 0, r = n - 1; while (l < r) { int m = l + ((r - l) >> 1); if (nums[m] < target) l = m + 1; else r = m; } return nums[l] == target ? l : -1; } int right(vector<int>& nums, int target) { int n = nums.size(), l = 0, r = n - 1; while (l < r) { int m = l + ((r - l + 1) >> 1); if (nums[m] > target) r = m - 1; else l = m; } return r; } };
相关文章推荐
- iOS 以byte数组作为密钥的3des加密
- 最短路算法之SPFA算法
- 单例模式常用方法
- noip1999 Cantor表 (找规律)
- C#实现判断一个时间点是否位于给定时间区间的方法
- C源码@数据结构与算法->AVL树
- 扩展欧几里得学习小记
- laravel (5.1) & Ember.js (1.13.0) 的整合
- 网站内部优化的六个基本要点
- [POJ2104] K-th Number/[POJ2761] Feed the dogs
- 懒得笔记5 spring aop 整合hibernate 事务管理
- Map, Map and flatMap in Scala
- 冒泡排序算法
- android中使用JSOUP如何解析网页数据详述
- nc后台两张单同名字字段数据交换
- C/C++混合编程出现:预编译头文件来自编译器的早期版本,或者预编译头为 C++ 而在 C 中使用它(或相反)问题的解决方案
- PAT 1078. Hashing (25)
- Android编码规范
- Spring MVC入门教程(一)
- SAP FICO期初开账存货导入尾差