又是二分查找
var searchRange = function (nums, target) { var left = 0, right = nums.length - 1; while (left <= right) { var mid = left + ((right - left) >> 1); if (nums[mid] == target) { //开始三个分支的处理 var begin = mid while (nums[begin - 1] == target) { --begin } var end = mid while (nums[end + 1] == target) { ++end } return [begin, end] break } else if (nums[mid] < target) {//[1,2,3,4,5,6,7], mid = 4, target = 5 left = mid + 1//left只能往mid靠 } else { right = mid - 1//right只能往mid靠 } } return [-1, -1] };
来源:https://www.cnblogs.com/rubylouvre/p/12044026.html