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].题目的意思是,输入一个升序排列的整数数组和一个目标值。咱们要找出这个目标数字在数组中的存在区间,并以数组形式返回这个区间。若是这个数字不存在于数组之中,则返回{-1.-1}。要求题目必须在O(logn)数组
For example,
输入数组[5, 7, 7, 8, 8, 10]和目标值8,
返回[3, 4].指针
public int[] searchRange(int[] nums, int target) { int[] res = {-1,-1}; int leftIndex = findIndex(nums,target,true); if(leftIndex == nums.length || nums[leftIndex] != target){ return res; } res[0] = leftIndex; res[1] = findIndex(nums,target,false)-1; return res; } public int findIndex(int[] nums,int target,boolean left){ int low = 0; int high = nums.length; while(low < high){ int mid = (low + high)/2; if(nums[mid] > target ||(left && target == nums[mid])){ high = mid; }else{ low = mid +1; } } return low; }