1、问题描述
Given an array of integers sorted in ascending order, 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]
.
给定一个按照上升排序的数组和一个数,找出这个数在该数组中的开始位置和结束位置。如果该数不存在数组中。返回[-1,-1].
2、问题分析
题目要求在log(N)的时间内。选择二分查找,现在数组中找出该数的一个位置,然后向左右两边扫描,找出左边的位置和右边的位置。
3、代码
1 vector<int> searchRange(vector<int>& nums, int target) { 2 // 数组是有序的 ,先用二分查找找出一个目标数。然后向两边寻找 3 4 vector<int> ans; 5 6 if(nums.size() == 0) 7 { 8 ans.push_back(-1); 9 ans.push_back(-1); 10 return ans; 11 } 12 13 int left = 0,right = nums.size()-1; 14 int index = -1; 15 while(left <= right) 16 { 17 int mid = left + (right - left)/2; 18 if(nums[mid] == target) 19 { 20 index = mid; 21 break; 22 } 23 24 else if( nums[mid] > target ) 25 right = mid -1; 26 else 27 left = mid + 1; 28 } 29 30 // target doesn't exist in array 31 if( index == -1) 32 { 33 ans.push_back(-1); 34 ans.push_back(-1); 35 return ans; 36 } 37 38 // target exist in array 39 40 int indexL = index; 41 int indexR = index; 42 while( nums[indexL] == target && indexL >= 0 ) indexL--; 43 while( nums[indexR] == target && indexR < nums.size() ) indexR++; 44 45 int n = nums.size(); 46 ans.push_back(indexL+1); 47 ans.push_back(indexR-1); 48 49 return ans;