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
return
Given
[5, 7, 7, 8, 8, 10] and target value 8,return
[3, 4].
这道题用两次二分法分别确定左边界和右边界
时间复杂度O(logn) 空间复杂度是O(1)public class Solution {
public int[] searchRange(int[] nums, int target) {
int[] res = {-1, -1};
if (nums == null || nums.length == 0) {
return res;
}
int left = 0;
int right = nums.length - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (target > nums[mid]) {
left = mid + 1;
} else {
right = mid - 1;
}
}
int start = 0;
int end = nums.length - 1;
while (start <= end) {
int mid = (start + end) / 2;
if (target >= nums[mid]) {
start= mid + 1;
} else {
end = mid - 1;
}
}
if (left <= end) {
res[0] = left;
res[1] = end;
}
return res;
}
}
public class Solution {
public int[] searchRange(int[] A, int target) {
int [] result = {-1,-1};
if (A.length == 0){
return result;
}
int str = 0;
int end = A.length - 1;
int mid;
// search for left bound
while (str + 1 < end){
mid = str + (end - str) / 2;
if (A[mid] < target){
str = mid;
} else if (A[mid] == target){
end = mid;
} else {
end = mid;
}
}
if (A[str] == target){
result[0] = str;
} else if (A[end] == target){
result[0] = end;
} else {
result[0] = result[1] = -1;
return result;
}
// search for right bound
str = 0;
end = A.length - 1;
while (str + 1 < end){
mid = str + (end - str) / 2;
if (A[mid] < target){
str = mid;
} else if (A[mid] == target){
str = mid;
} else {
end = mid;
}
}
if (A[end] == target){
result[1] = end;
} else if (A[str] == target){
result[1] = str;
} else {
result[0] = result[1] = -1;
return result;
}
return result;
}
}
没有评论:
发表评论