Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
Ray-56 opened this issue Dec 1, 2020 · 2 comments
Open
Labels

Comments

@Ray-56
Copy link
Owner

Ray-56 commented Dec 1, 2020

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

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

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

进阶:

  • 你可以设计并实现时间复杂度为 O(log n) 的算法解决此问题吗?

示例 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]

提示:

  • 0 <= nums.length <= 105
  • -109 <= nums[i] <= 109
  • nums 是一个非递减数组
  • -109 <= target <= 109
@Ray-56 Ray-56 added the 中等 label Dec 1, 2020
@Ray-56
Copy link
Owner Author

Ray-56 commented Dec 1, 2020

复杂度 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
Copy link
Owner Author

Ray-56 commented Dec 1, 2020

复杂度 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;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant