https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/
二分查找详解:
class Solution { public int[] searchRange(int[] nums, int target) { int left=left_bound(nums,target); int right=right_bound(nums,target); return new int[]{left,right}; } int left_bound(int[] nums, int target) { int l=0,h=nums.length; while(l<h){ int mid=l+(h-l)/2; if(nums[mid]==target){ h=mid; } else if(nums[mid]>target){ h=mid; } else if(nums[mid]<target){ l=mid+1; } } if(l==nums.length) return -1; return nums[l]==target ? l : -1; } int right_bound(int[] nums, int target) { int l=0,h=nums.length; while(l<h){ int mid=l+(h-l)/2; if(nums[mid]==target){ l=mid+1; }else if(nums[mid]<target){ l=mid+1; } else{ h=mid; } } if(l==0) return -1; return nums[l-1]==target ? l-1 :-1; } }