Skip to content

Latest commit

 

History

History
61 lines (53 loc) · 1.56 KB

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

File metadata and controls

61 lines (53 loc) · 1.56 KB

给定一个按照升序排列的整数数组 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]

solution:

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var searchRange = function(nums, target, start = 0, end = nums.length - 1) {
    if (nums.length === 0 || (nums.length === 1 && nums[0] !== target)) return [-1, -1]
    console.log(target, start, end)
    const mid = start + ((end - start) >> 1)
    if (start === end) {
        if (nums[start] === target) return findPos(nums, start, target)
        else return [-1, -1]
    } else if (start > end) {
        return [-1, -1]
    } else if (nums[mid] === target) {
        return findPos(nums, mid, target)
    } else if (nums[mid] < target) {
        return searchRange(nums, target, mid + 1, end)
    } else {
        return searchRange(nums, target, start, mid - 1)
    }
    function findPos(nums, pos, tar) {
        const res = [pos, pos]
        let i = pos - 1, j = pos + 1
        while(nums[i] === tar || nums[j] === tar) {
            if (nums[i] === tar) {
                res[0] = i
                i--
            }
            if (nums[j] === tar) {
                res[1] = j
                j++
            }
        }
        return res
    }
};