在排序数组中查找元素的第一个和最后一个位置 JS

我胡汉三又回来了,这种为啥超出时间限制,我实在受不了就要来个indexOf和lastIndexof了

var searchRange = function(nums, target) {
    let left=0;
    let right=nums.length-1,mid;
    if(left>right)return [-1,-1]
    while(left<=right){
        mid=(left+right)>>1
        if(nums[mid]===target)break;
        if(nums[mid]>target)right=mid-1
        else left=mid+1
    }
    let i,j=mid;
    while(nums[i]===nums[i-1])i--
    while(nums[j]===nums[j+1])j++
    return [i,j]
    
};

你可能感兴趣的:(javascript,排序算法,leetcode)