Search for a Range ——LeetCode
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]
.
题目大意:给定一个排序好的数组,找到指定数的起始范围,如果不存在返回[-1,-1];
解题思路:要求O(lgN)时间复杂度,二分查找。
public int[] searchRange(int[] nums, int target) { int[] res = new int[2]; if(nums==null||nums.length==0){ return res; } res[0]=getLow(nums,target,0,nums.length-1); res[1]=getHigh(nums,target,0,nums.length-1); return res; } int getLow(int[] nums,int target,int low,int high){ int mid=(low+high)>>1; if(low>high){ return -1; } if(low==high){ return nums[low]==target?low:-1; } if(nums[mid]==target){ return getLow(nums,target,low,mid); } if(nums[mid]<target){ low=mid+1; return getLow(nums,target,low,high); }else{ high=mid-1; return getLow(nums,target,low,high); } } int getHigh(int[] nums,int target,int low,int high){ int mid=(low+high)>>1; if(low>high){ return -1; } if(low==high){ return nums[low]==target?low:-1; } if(nums[mid]==target){ int tmp=getHigh(nums,target,mid+1,high); int max=Math.max(tmp,mid); return max; } if(nums[mid]<target){ low=mid+1; return getHigh(nums,target,low,high); }else{ high=mid-1; return getHigh(nums,target,low,high); } }