34. Find First and Last Position of Element in Sorted Array(js)

34. Find First and Last Position of Element in Sorted Array

Given an array of integers nums sorted in ascending order, 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].

Example 1:

Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]

Example 2:

Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]
题意:给定一个排好序的数字数组,返回匹配到target的第一项和第二项的索引
代码如下:
/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var searchRange = function(nums, target) {
    
    var res=[];
    var count=0;
    for(var i=0;i<nums.length;i++){
        if(nums[i]===target){ res.push(i);count++; break;}
    }
    for(var i=nums.length-1;i>=0;i--){
        if(nums[i]===target) {res.push(i);count++; break;}
    }
    if(count==2) return res;
    return [-1,-1]
};
原文地址:https://www.cnblogs.com/xingguozhiming/p/10409327.html