【LeetCode】34. Search for a Range
2014-12-17 23:01
441 查看
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
For example,
Given
return
由于O(logn)时间要求,显然用二分查找。
思路是先用二分查找找到其中一个target,找不到则返回默认的ret值[-1, -1]
找到之后从这个位置往两边递归进行二分查找进行范围的拓展。
具体来说,ret[0]不断向左扩展,ret[1]不断向右扩展。
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].
由于O(logn)时间要求,显然用二分查找。
思路是先用二分查找找到其中一个target,找不到则返回默认的ret值[-1, -1]
找到之后从这个位置往两边递归进行二分查找进行范围的拓展。
具体来说,ret[0]不断向左扩展,ret[1]不断向右扩展。
class Solution { public: vector<int> searchRange(int A[], int n, int target) { vector<int> ret(2, -1); int left; int right; int low = 0; int high = n-1; while((left = binarySearch(A, low, high, target)) != -1) { ret[0] = left; high = left-1; } low = 0; high = n-1; while((right = binarySearch(A, low, high, target)) != -1) { ret[1] = right; low = right+1; } return ret; } int binarySearch(int A[], int left, int right, int target) { while(left <= right) { int mid = left + (right-left) / 2; if(A[mid] == target) return mid; else if(A[mid] < target) left = mid + 1; else right = mid - 1; } return -1; } };
相关文章推荐
- Leetcode_34_Search for a Range
- [LeetCode]34.Search for a Range
- Search for a Range - LeetCode 34
- Leetcode34 Search for a Range
- 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
- 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