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]
.
这题比较简单,就是边界的时候范围需要注意一下,我的方法先用二分法找到那个目标所在的位置,然后从那个位置增加和减少index直到不等于目标,于是就得到一个索引范围。代码如下:
1 class Solution { 2 public: 3 vector searchRange(vector & nums, int target) { 4 int len = nums.size(); 5 int start = 0; 6 int end = len; 7 vector result; 8 findStartEnd(nums,start,end,target,result); 9 if(result.size()==0){10 result.push_back(-1);11 result.push_back(-1);12 }13 return result;14 }15 16 void findStartEnd(vector &nums,int start,int end,int target,vector & result){17 int mid = (start+end)/2;18 if(start<=mid&&end>=mid){19 if(nums[mid]>target){20 if(start == mid) mid = mid-2;21 findStartEnd(nums,start,mid,target,result);22 }23 else if(nums[mid]< end ;i++){30 if(nums[i]!=nums[mid]){31 tail = i-1;32 break;33 }34 tail = i;35 }36 for(int j = mid-1 ;j>=start;j--){37 if(nums[j]!=nums[mid]){38 front = j+1;39 break;40 }41 front = j;42 }43 result.push_back(front);44 result.push_back(tail);45 }46 }47 }48 };