题目:
给定一个已经升序排序的整形数组,找出给定目标值的开始位置和结束位置。
你的算法时间复杂度必须是 O(log n) 级别。
如果在数组中找不到目标,返回 [-1, -1]
。
例如:
给出 [5, 7, 7, 8, 8, 10]
和目标值 8,
返回 [3, 4]
。
分析:
自己写的第一种方法就是普通二分查找,找到target数字之后,分别向前向后遍历,直到找到一个不等于target的数字。
这个最差的情况到了O(n)
看了网上的一种方法,试了试,两次二分查找,第一次找出开始索引,第二次查找找出结束索引 。
但是方法二所用的时间比方法一还要多。。
代码:
class Solution {//方法一
public int[] searchRange(int[] nums, int target) {
int[] index = new int[2];
index[0] = -1; index[1] = -1;
serch(index,nums,target,0,nums.length-1);
return index;
}
public static void serch(int[] index, int[] nums, int target, int begin, int end) {
if (begin > end)
return;
int mid = (begin + end) / 2;
if (nums[mid] == target) {
index[0] = mid;
index[1] = mid;
while (index[1] < nums.length && nums[index[1]] == target)
index[1]++;
index[1]--;
while (index[0] > -1 && nums[index[0]] == target)
index[0]--;
index[0]++;
}
if (nums[mid] < target)
serch(index, nums, target, mid + 1, end);
if (nums[mid] > target)
serch(index, nums, target, begin, mid - 1);
}
}
class Solution {//方法二
public int[] searchRange(int[] nums, int target) {
int[] index = new int[2];
index[0] = -1; index[1] = -1;
if(nums.length==0)
return index;
serch2(index,nums,target);
return index;
}
public static void serch2(int[] index, int[]nums, int target){
index[0] = 0;
index[1] = nums.length-1;
int low = 0;
int high = nums.length-1;
while (low < high){//找到开始索引
int mid = (low+high)/2;
if (nums[mid] < target)
low = mid+1;
else
high = mid;
}
index[0] = nums[low]==target? low:-1;
low = 0; high = nums.length-1;
while(low < high){//找到结束的索引
int mid = (high + low+1) / 2;
if (nums[mid] > target)
high = mid-1;
else
low = mid;
}
index[1] = nums[high]==target?high:-1;
}
}