Leetcode 34. Search for a Range
2017-01-27 07:55
387 查看
Given an array of integers sorted in ascending order, 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].
s思路:
1. 简单但不粗暴的做法:用lower_bound和upper_bound两个函数即可!
2. 肯定是要调用两次binary search来找到左右两个边界点!第一次,找比target小的最大值的位置;第二次找比target大的最小值的位置。这两个位置如果存在,则是求的范围!
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].
s思路:
1. 简单但不粗暴的做法:用lower_bound和upper_bound两个函数即可!
2. 肯定是要调用两次binary search来找到左右两个边界点!第一次,找比target小的最大值的位置;第二次找比target大的最小值的位置。这两个位置如果存在,则是求的范围!
class Solution { public: vector<int> searchRange(vector<int>& nums, int target) { // int left=0,right=nums.size()-1; vector<int> res{-1,-1}; if(nums.empty()) return res; //第一次binary search,找左边边界 while(left<=right){ int mid=left+(right-left)/2; if(nums[mid]>=target){ right=mid-1; }else left=mid+1; } if(left>=nums.size()||nums[left]!=target) return res; //不厌其烦的说:对left是计算出来的,就要只带保护,即:先确定是否left在范围内!! res[0]=left; //第二次binary search,找右边边界! right=nums.size()-1; while(left<=right){ int mid=left+(right-left)/2; if(nums[mid]>target){ right=mid-1; }else left=mid+1; } res[1]=right; return res; } };
相关文章推荐
- LeetCode 34.Search for a Range
- [leetcode 34] Search for a Range
- LeetCode_34---Search for a Range
- [Leetcode 34, Medium] Search for a Range
- leetcode 34: Search for a Range
- LeetCode 34 Search for a Range
- 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 34] Search for a Range
- leetcode 34 -- 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)
- LeetCode 34 Search For A Range 二叉查找相关(二)
- 【LeetCode 34】Search for a Range
- leetCode 34.Search for a Range (搜索范围) 解题思路和方法
- leetcode_34——Search for a Range(二分查找)