首页 > 代码库 > [leetcode]Search for a Range
[leetcode]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 ofO(logn).
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]
.
基本思路:
此题可以用二分查找法解决。
如果数组中没有target,可以在O(lgn)时间完成。
如果数组中有target,当发现target后,对前后的内容继续用二分法 查找这样的位置pos 。
- 前面的pos需要满足 A[pos] < target && A[pos+1] == target. pos+1即是开始位置。
- 后面的pos需要满足 A[pos] > target && A[pos-1] == target . pos-1是结束位置。
代码:
vector<int> searchRange(int A[], int n, int target) { //C++ vector<int> result(2); int low = 0, high = n-1; int mid, begin = -1, end = -1; while(low <= high) { mid = (low+high)/2; if(A[mid] > target) high = mid - 1; else if(A[mid] < target) low = mid + 1; else { begin = mid; end = mid; //get begin if(low <= begin -1){ while((low <= begin-1) && !(A[low]<target && A[low+1] == target) ) { mid = (low + begin-1)/2; if(A[mid] < target) low = mid+1; else begin = mid; } if(A[low]<target && A[low+1] == target) begin = low+1; } //get end if(high >= end+1){ while((high >= end+1) &&!(A[high]>target && A[high-1] == target)) { mid = (high + end +1)/2; if(A[mid] > target) high = mid - 1; else end = mid; } if(A[high]>target && A[high-1] == target) end = high - 1; } break; } } result[0] = begin; result[1] = end; return result; }
[leetcode]Search for a Range
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。