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; }