关于二分,一定要看这篇文章,写得真的很好~~~尤其是对寻找目标数最左边的索引问题的形象解释,很棒棒~~
https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/solution/er-fen-cha-zhao-suan-fa-xi-jie-xiang-jie-by-labula/
var searchRange = function(nums, target) {
var first=findLeftBinary(nums,target);
var last=findLeftBinary(nums,target+1)-1;
if(nums[first]!=target||first==nums.length) return [-1,-1];
else return [first,last];
};
function findLeftBinary(nums,target){
let l=0,h=nums.length;//注意h的取值
while(l<h){
var m=Math.floor(l+(h-l)/2);
if(nums[m]>=target) h=m;
else l=m+1;
}
return l;
}