一、原题
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]
.
二、中文
给定一个排好序的数组,同时给定一个要查找的值 ,找出这个数在数组中的出现在起始和结束位置。
算法的时间复杂度要求为log(N)。
如果没有找到就返回
[-1, -1]
三、举例
数组是1,3,5,5,5,7 和目标元素是5,最后得到的左边的下标是2,右边的下标是4
四、思路
由于效率是logN,首先想到的就是使用二分查找的方式来进行,对找到的中间元素进行一次判断就行了
五、程序
package code;
public class LeetCode24{
public static void main(String args[]){
int nums[] = new int[]{1, 3, 5, 5, 5, 6, 7, 9};
int res[] = new int[2];
res = searchMidIndex(nums, 0, nums.length, 5);
System.out.println("First = "+res[0]+"\nLast = "+res[1]);
}
public static int[] findIndexOfTarget(int[] nums, int target){
if(nums == null || nums.length < 1 ){
return new int[]{-1, -1};
}
int start = 0;
int end = nums.length-1;
int res[] = new int[2];
res = searchMidIndex(nums, start, end, target);
return res;
}
/**
* 通过二分查找的方式来找到目标元素
* @param nums
* @param start
* @param end
* @param target
*/
public static int[] searchMidIndex(int[] nums, int start, int end, int target){
int first = -1, last = -1;
int res[] = new int[2];
int mid = start + ((end - start) >> 1);
//如果中间值恰好是目标值,分别搜索两个数组的左右两边
if(nums[mid] == target){
//左右移动来寻找最大和最小的index
first = mid;
last = mid;
while(nums[first-1] == target){
first--;
}
while(nums[last+1] == target){
last++;
}
}
//如果中间值大于目标值,说明目标在左边
if (nums[mid] > target) {
searchMidIndex(nums, start, mid-1, target);
}
//如果中间值小于目标值,说明在右边
if(nums[mid] < target){
searchMidIndex(nums, mid+1, end, target);
}
res[0] = first;
res[1] = last;
return res;
}
}