LeetCode Search for a Range
2015-02-25 20:43
381 查看
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
题意:求已排序数组出现某个数的范围。
思路:两次二分,找出左右边界
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].
题意:求已排序数组出现某个数的范围。
思路:两次二分,找出左右边界
class Solution { public: vector<int> searchRange(int A[], int n, int target) { int left = 0, right = n; while (left < right) { int mid = left + right >> 1; if (A[mid] >= target) right = mid; else left = mid + 1; } int ansLeft = left; left = 0, right = n; while (left < right) { int mid = left + right >> 1; if (A[mid] > target) right = mid; else left = mid + 1; } if (A[ansLeft] != target) return vector<int>{-1, -1}; else return vector<int>{ansLeft, left-1}; } };
相关文章推荐
- leetcode -- Search for a Range (TODO)
- LeetCode 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 89] 34 Search for a Range
- LeetCode 38: 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] Search for a Range 解题报告
- LeetCode: Search for a Range
- leetcode 96: 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 - Search for a Range