Description:
Given an array of integers nums 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].
Example 1:
Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]
Example 2:
Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]
题意:给定一个按照升序排列的数组,要求找出目标数字所在的下标的范围(目标数字在数组中可能不止一个),并且要求时间复杂度在 O(log n);
解法:既然数组时已经排序好的了,那么我们只要可以找到其中的一个目标数字,从这个数字向两边扩散,就可以找到所有我们想要找到的目标数字了;因此可以先利用二分查找找到其中的一个目标数字;
Java
class Solution {
public int[] searchRange(int[] nums, int target) {
if(nums.length == 0){
return new int[] {-1, -1};
}
int left = 0;
int right = nums.length - 1;
int mid = (left + right) / 2;
while(left <= right){
if(nums[mid] == target) break;
else if(nums[mid] > target) right = mid - 1;
else left = mid + 1;
mid = (left + right) / 2;
}//find one position of the target digit
if(nums[mid] != target) return new int[] {-1, -1};
int st = mid;
int ed = mid;
while(st >= 0 || ed < nums.length){
boolean isMatch = false;
if(st > 0 && nums[st-1] == target) {st--; isMatch = true;}
if(ed < nums.length - 1 && nums[ed+1] == target) {ed++; isMatch = true;}
if(!isMatch) break;
}
return new int[] {st, ed};
}
}
C++
class Solution {//C++
public:
vector<int> searchRange(vector<int>& nums, int target) {
vector<int> result (2, -1);
if(nums.size() == 0){
return result;
}
int left = 0;
int right = nums.size() - 1;
int mid = (left + right) / 2;
while(left <= right){
if(nums[mid] == target) break;
else if(nums[mid] > target) right = mid - 1;
else left = mid + 1;
mid = (left + right) / 2;
}
if(nums[mid] != target){
return result;
}
int st = mid;
int ed = mid;
while(st >= 0 || ed < nums.size()){
bool isMatch = false;
if(st > 0 && nums[st-1] == target) {st--; isMatch = true;}
if(ed < nums.size() - 1 && nums[ed+1] == target) {ed++; isMatch = true;}
if(!isMatch) break;
}
result[0] = st;
result[1] = ed;
return result;
}
};