(Js) Leetcode 34. Find the first and last position of the element in the sorted array

topic:

Given an integer array nums arranged in ascending order, and a target value target. Find the start and end positions of the given target value in the array.

If there is no target value target in the array, return [-1, -1].

Advanced:

Can you design and implement an O(log n) algorithm to solve this problem?

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]
Example 3:

Input: nums = [], target = 0
Output: [-1,-1]

prompt:

0 <= nums.length <= 105
-109 <= nums[i] <= 109
nums is a non-decreasing array
-109 <= target <= 109

Ideas:

Reference Official ideas

Code:

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var searchRange = function(nums, target) {
    let ans = [-1, -1];
    const leftIdx = binarySearch(nums, target, true);
    const rightIdx = binarySearch(nums, target, false) - 1;
    if (leftIdx <= rightIdx && rightIdx < nums.length && nums[leftIdx] === target && nums[rightIdx] === target) {
        ans = [leftIdx, rightIdx];
    } 
    return ans;
};

const binarySearch = (nums, target, lower) => {
    let left = 0, right = nums.length - 1, ans = nums.length;
    while (left <= right) {
        const mid = Math.floor((left + right) / 2);
        if (nums[mid] > target || (lower && nums[mid] >= target)) {
            right = mid - 1;
            ans = mid;
        } else {
            left = mid + 1;
        }
    }
    return ans;
}

operation result:

 

Guess you like

Origin blog.csdn.net/M_Eve/article/details/113192427