Search for a Range
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]
.
https://leetcode.com/problems/search-for-a-range/
给定有序的数列,要求找出目标,要求时间复杂度O(logn),二分法。
1 /** 2 * @param {number[]} nums 3 * @param {number} target 4 * @return {number[]} 5 */ 6 var searchRange = function(nums, target) { 7 var len = nums.length, start = 0; end = len - 1; 8 while(start <= end){ 9 var index = parseInt((start + end) / 2); 10 if(nums[index] === target){ 11 start = end = index; 12 while(start - 1 >= 0 && nums[start - 1] === target) start--; 13 while(end + 1 <= len - 1 && nums[end + 1] === target) end++; 14 return [start, end]; 15 }else if(nums[index] > target){ 16 end = index - 1; 17 }else if(nums[index] <target){ 18 start = index + 1; 19 } 20 } 21 return [-1, -1]; 22 };