题目:

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];
};

 

相关文章:

  • 2022-01-13
  • 2021-08-05
  • 2022-02-20
  • 2021-12-28
  • 2021-08-21
猜你喜欢
  • 2021-04-10
  • 2021-10-03
  • 2021-08-06
相关资源
相似解决方案