Description:
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].
Ex:
[5, 7, 7, 8, 8, 10] and target value 8—–[3, 4]
[5, 7, 7, 8, 10] and target value 8—–[3 , 3]
[5, 7, 7, 10] and target value 8—-[-1, -1]
问题描述:
搜索范围,给一串递增的数组和目标元素,返回目标元素在数组中出现的起始位置索引,如果目标元素不存在数组中,返回[-1 -1]
解法一:
思路:
总体上看是两次二分查找,时间复杂度为O(logn)
Code:
public class Solution {
public int[] searchRange(int[] nums, int target) {
int[] result = new int[2];
result[1] = findFirst(nums,target);
result[0]= findLast(nums,target);
return result;
}
private int findFirst(int[] nums, int target){
int idx = -1;
int start = 0;
int end = nums.length -1;
while(start <= end){
int mid = start + (end - start)/2;
if(nums[mid] > target){
end = mid - 1;
}
else{
start = mid + 1;
}
if(nums[mid] == target) idx = mid;
}
return idx;
}
private int findLast(int[] nums,int target){
int idx = -1;
int start = 0;
int end = nums.length -1;
while(start <= end){
int mid = start + (end - start)/2;
if(nums[mid] < target){
start = mid + 1;
}
else{
end = mid -1;
}
if(nums[mid] == target) idx = mid;
}
return idx;
}
}
备注
这里的两个函数太相似了,而且逻辑有点昏。。。。