题目
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的值的位置,然后分别向左右递减或递加。
class Solution {
public:
vector<int> searchRange(int A[], int n, int target) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int left = 0;
int right = n-1;
int mid = 0;
vector<int> res(2,0);
while(left<=right)
{
mid = (left+right)/2;
if(A[mid]==target)
break;
else if(A[mid]>target)
right = mid-1;
else
left = mid+1;
}
if(left>right)
{
res[0] = -1;
res[1] = -1;
}
else
{
left = mid;
while(left>=0 && A[left]==target)
left--;
res[0] = left+1;
right = mid;
while(right<=n-1 && A[right]==target)
right++;
res[1] = right-1;
}
return res;
}
};
注意:二分查找时,right=mid+1;left=mid-1; 而不是right=mid;left=mid;否则相等时退不出来。
思路二:分别二分找到左边界和右边界
class Solution {
public:
vector<int> searchRange(int A[], int n, int target) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<int> res(2,0);
int left = 0;
int right = n-1;
while(left<=right)
{
int mid = (left+right)/2;
if(target<=A[mid])
right = mid-1;
else
left = mid+1;
}
int leftmost = left;
left = leftmost;
right = n-1;
while(left<=right)
{
int mid = (left+right)/2;
if(A[mid]<=target)
left = mid+1;
else
right = mid-1;
}
int rightmost = right;
if(A[leftmost]!=target || A[rightmost]!=target)
{
res[0] = -1;
res[1] = -1;
}
else
{
res[0] = leftmost;
res[1] = rightmost;
}
return res;
}
};
最新 java (上述版本有 bug)
public class Solution {
public int[] searchRange(int[] nums, int target) {
if(nums == null || nums.length == 0){
return new int[]{-1,-1};
}
int left = 0;
int right = nums.length-1;
while(left <= right){
int mid = (right+left)/2;
if(target <= nums[mid]){
right = mid-1;
} else {
left = mid+1;
}
}
if(left < 0 || left > nums.length-1) {
return new int[]{-1,-1};
}
int leftmost = left;
left = leftmost;
right = nums.length-1;
while(left <= right){
int mid = (right+left)/2;
if(nums[mid] <= target){
left = mid+1;
} else {
right = mid-1;
}
}
if(right < 0 || right > nums.length-1) {
return new int[]{-1,-1};
}
int rightmost = right;
int[] res = new int[2];
if(nums[leftmost] != target || nums[rightmost] != target)
{
res[0] = -1;
res[1] = -1;
}
else
{
res[0] = leftmost;
res[1] = rightmost;
}
return res;
}
}
本文介绍了一种算法,用于在已排序的整数数组中找出给定目标值的起始和结束位置,通过两次二分查找确定目标值的左右边界,确保了算法的时间复杂度为O(log n)。
3254

被折叠的 条评论
为什么被折叠?



