首页 > 代码库 > 【LeetCode】Search for a Range
【LeetCode】Search for a Range
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 [-1, -1]
.
For example,
Given [5, 7, 7, 8, 8, 10]
and target value 8,
return [3, 4]
.
由于O(logn)时间要求,显然用二分查找。
思路是先用二分查找找到其中一个target,找不到则返回[-1, -1]
找到之后从这个位置往两边递归进行二分查找进行范围的拓展。
部分参考了
class Solution {public: vector<int> searchRange(int A[], int n, int target) { vector<int> ret(2, -1); int ind = Helper(A, 0, n-1, target); if(ind != -1) {//find one target int left = ind; int right = ind; ret[0] = left; ret[1] = right; //recursively extend left towards 0 while((left = Helper(A, 0, left-1, target)) != -1) ret[0] = left; //recursively extend right towards n-1 while((right = Helper(A, right+1, n-1, target)) != -1) ret[1] = right; } return ret; } int Helper(int A[], int low, int high, int target) {//binary search while(low <= high) { int mid = low + (high-low)/2; if(A[mid] == target) return mid; else if(A[mid] > target) high = mid-1; else low = mid+1; } return -1; }};
【LeetCode】Search for a Range
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。