find-first-and-last-position-of-element-in-sorted-array

The title

Given an array of integers in ascending order, nums, and a target value, target. Find the starting and ending positions of the given target value in the array.

Your algorithm must be order log n in time.

If no target value exists in the array, return [-1, -1]. Example 1:

Input: nums = [5,7,7,8,8,10] target = 8Copy the code

Example 2:

Input: nums = [5,7,7,8,8,10], target = 6Copy the code

parsing

First find the starting position using indexOf, then work backwards to find the last index of the result

code

var searchRange = function(nums, target) {
    let i = nums.indexOf(target);
    if (i < 0) return [- 1.- 1];
    let start = i;
    let end = nums.length - 1;
    while (end >= start) {
        if (nums[end] === target) {
            return[start, end] } end--; }};Copy the code