[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 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]
.
题目要求:查找有序数组,找到target的范围,如果target不存在于数组,返回[-1, -1]。
思路:和二分查找的思路类似,找到target之后,将start和end同时指向mid,终止查找。然后start向左搜索,end向右搜索,定位区间。
注意start和end下标不要越界的问题(第一次WA就是因为这个错误)。
代码
class Solution { public: vector<int> searchRange(int A[], int n, int target) { // Note: The Solution object is instantiated only once and is reused by each test case. vector<int> range; if(n==0 || A==NULL) { range.push_back(-1); range.push_back(-1); return range; } int l=0, r=n-1, start=-1, end=-1; int mid = 0; bool success_flag = false; while(l<=r) { mid = (l+r)/2; if(A[mid] == target) { start = mid; end = mid; success_flag = true; break; } else{ if(A[mid]>target) // ture left { r = mid-1; } else l = mid+1; } } // search range if(success_flag) { while(A[start-1]==target && start>0) --start; while(A[end+1] == target && end<n-1) ++end; } range.push_back(start); range.push_back(end); return range; } };