问题描述:
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]
.
解释:
给一串数组,在其中找出某一个数第一次出现和最后一次出现的位置,放在一个数组返回,没找到就返回[-1,-1];如给定数组[5, 7, 7, 8, 8, 10]和数字8,结果就是[3,4]
程序(用js写的):
1 /**
2 * @param {number[]} nums
3 * @param {number} target
4 * @return {number[]}
5 */
6 var searchRange = function(nums, target) {
7 var res=[];
8 for(var i=0;i<nums.length;++i){
9 if(nums[i]==target){
10 res.push(i);
11 }
12 }
13 if(res.length==0){
14 return [-1,-1];
15 }else{
16 return [res[0],res[res.length-1]];
17 }
18
19 };