[Leetcode] 34. Search for a Range 解题报告
2016-12-29 05:09
387 查看
题目:
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
思路:
这还是典型的二分查找,关键在于怎么定义二分查找的边界条件。偷懒的做法是直接利用STL中提供的upper_bound和lower_bound方法,见代码片段1;不过估计这时签证官不会善罢甘休的,要求你写出bug free的upper_bound和lower_bound代码。那么请看代码片段2吧!
代码:
1、偷懒做法:
2、完整做法:
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].
思路:
这还是典型的二分查找,关键在于怎么定义二分查找的边界条件。偷懒的做法是直接利用STL中提供的upper_bound和lower_bound方法,见代码片段1;不过估计这时签证官不会善罢甘休的,要求你写出bug free的upper_bound和lower_bound代码。那么请看代码片段2吧!
代码:
1、偷懒做法:
class Solution { public: vector<int> searchRange(vector<int>& nums, int target) { vector<int> ret(2, -1); auto it_start = lower_bound(nums.begin(), nums.end(), target); auto it_end = upper_bound(nums.begin(), nums.end(), target); if(it_start == it_end) return ret; ret[0] = distance(nums.begin(), it_start); ret[1] = distance(nums.begin(), it_end) - 1; return ret; } };
2、完整做法:
class Solution { public: vector<int> searchRange(vector<int>& nums, int target) { vector<int> ret = {-1, -1}; if(nums.size() == 0) return ret; int lower = lower_bound(nums, 0, nums.size() - 1, target); int upper = 4000 upper_bound(nums, lower, nums.size() - 1, target); // to accelerate if(lower == upper) return ret; ret[0] = lower; ret[1] = upper - 1; return ret; } private: int lower_bound(vector<int>& nums, int left, int right, int target) { while(left <= right) { int mid = left + (right - left) / 2; if(nums[mid] >= target) right = mid - 1; else left = mid + 1; } return left; } int upper_bound(vector<int>& nums, int left, int right, int target) { while(left <= right) { int mid = left + (right - left) / 2; if(nums[mid] > target) right = mid - 1; else left = mid + 1; } return left; } };
相关文章推荐
- [leetcode] 34. Search for a Range 解题报告
- leetCode 34.Search for a Range (搜索范围) 解题思路和方法
- LeetCode: Search for a Range 解题报告
- [LeetCode] Search for a Range 解题报告
- [LeetCode] Search for a Range 解题报告
- LeetCode: Search for a Range 解题报告
- leetCode 34.Search for a Range (搜索范围) 解题思路和方法
- LeetCode解题报告--Search for a Range
- leetcode-34 Search for a Range
- [LeetCode 34] Search for a Range
- LeetCode 34 — Search for a Range(C++ Java Python)
- Search for a Range - LeetCode 34
- leetcode_34——Search for a Range(二分查找)
- leetcode 34: Search for a Range
- [LeetCode]34 Search for a Range
- 【LeetCode】34. Search for a Range
- [Leetcode 89] 34 Search for a Range
- Leetcode_34_Search for a Range
- LeetCode 34 Search For A Range 二叉查找相关(二)
- LeetCode --- 34. Search for a Range