题目
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].
答案
class Solution {
public int[] searchRange(int[] nums, int target) {
if(nums.length == 0) return new int[]{-1,-1};
// Two binary search, the first searches for the start of the range, second for the end of the range
// Search start
int start_idx = -1;
int left = 0, right = nums.length - 1;
while(left <= right) {
int mid = left + (right - left ) / 2;
int num_mid = nums[mid];
if(target < num_mid) {
right = mid - 1;
}
else if(target == num_mid) {
start_idx = mid;
right = mid - 1;
}
else {
// target > num_mid
left = mid + 1;
}
}
// Search end
int end_idx = -1;
left = 0;
right = nums.length - 1;
while(left <= right) {
int mid = left + (right - left ) / 2;
int num_mid = nums[mid];
if(target < num_mid) {
right = mid - 1;
}
else if(target == num_mid) {
end_idx = mid;
left = mid + 1;
}
else {
// target > num_mid
left = mid + 1;
}
}
if(start_idx == -1) return new int[]{-1,-1};
return new int[]{start_idx, end_idx};
}
}
网友评论