Ray-56 / like-algorithms

每天一道算法题,突破自己
2 stars 1 forks source link

✅34. 在排序数组中查找元素的第一个和最后一个位置 #175

Open Ray-56 opened 3 years ago

Ray-56 commented 3 years ago

34. 在排序数组中查找元素的第一个和最后一个位置

给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。

如果数组中不存在目标值 target,返回 [-1, -1]。

进阶:

示例 1:

输入:nums = [5,7,7,8,8,10], target = 8
输出:[3,4]

示例 2:

输入:nums = [5,7,7,8,8,10], target = 6
输出:[-1,-1]

示例 3:

输入:nums = [], target = 0
输出:[-1,-1]

提示:

Ray-56 commented 3 years ago

复杂度 O(n)

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var searchRange = function(nums, target) {
    let first = -1;
    let last = -1;
    for (let i = 0; i < nums.length; i++) {
        if (target === nums[i]) {
            if (first === -1) {
                first = i;
            }
            last = i
        }
    }
    return [first, last];
};
Ray-56 commented 3 years ago

复杂度 O(log n)

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

function binarySearch(nums, target, lower) {
    let left = 0;
    let right = nums.length - 1;
    let 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;
}