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

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

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

你的算法时间复杂度必须是 O(log n) 级别。

如果数组中不存在目标值,返回 [-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]

来源:https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/

题解
二分查找,结果就是第一个大于等于target的位置第一个大于target的位置-1

var searchRange = function (nums, target) {
    let x = 0, y = nums.length - 1;
    /* 找出第一个大于等于target的位置 */
    while (x <= y) {/* 退出条件x=y+1 */
        let m = x + Math.floor(y - x >> 1);
        /* 只要中间值大于target,不断往左边走,
           y最终就是最后一个小于target的位置 */
        if (nums[m] >= target) y = m - 1;
        /* 遇到小于往右边走,x最终就是第一个大于等于target的位置 */
        else x = m + 1;
    }
    let res1 = nums[x] === target ? x : -1;

    /* 找出第一个大于target的位置 */
    x = 0, y = nums.length - 1;
    while (x <= y) {/* 退出条件x=y+1 */
        let m = x + Math.floor(y - x >> 1);
        /* 只要中间值大于target,不断往左边走,
           y最终就是最后一个小于等于target的位置 */
        if (nums[m] > target) y = m - 1;
        /* 遇到小于往右边走,x最终就是第一个大于target的位置 */
        else x = m + 1;
    }
    let res2 = nums[y] == target ? y : -1;
    return [res1, res2];
};
let ans = searchRange([5, 7, 7, 8, 8, 10], 8)
console.log(ans)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章