【数组】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]
.
思路:
两个指针,一个从前往后找到第一个target,一个从后往前第一个找到target。
/** * @param {number[]} nums * @param {number} target * @return {number[]} */ var searchRange = function(nums, target) { var m=0,n=nums.length; for(var i=0;i<n;i++){ if(nums[i]==target){ break; } } if(i==nums.length){ return [-1,-1]; } for(var j=n-1;j>=i;j--){ if(nums[j]==target){ break; } } return [i,j]; };