[LeetCode] 34. Find First and Last Position of Element in Sorted Array

在有序数组中查找元素的第一个和最后一个位置。题意很简单,给了一个数组和一个数字A,问数字A第一次和最后一次在数组中出现的位置在哪里,若没有,return -1。例子,

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]

也是一道典型的二分法题目,思路是通过二分法思想分别找到第一个插入的位置和第二个插入的位置。

时间O(log n)

空间O(1)

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var searchRange = function(nums, target) {
    // corner case
    if (nums === null || nums.length === 0) {
        return [-1, -1];
    }
    // normal case
    let start = findFirst(nums, target);
    if (start === -1) {
        return [-1, -1];
    }
    let end = findLast(nums, target);
    return [start, end];
};

var findFirst = function(nums, target) {
    let start = 0;
    let end = nums.length - 1;
    while (start + 1 < end) {
        let mid = Math.floor(start + (end - start) / 2);
        if (nums[mid] < target) {
            start = mid;
        } else {
            end = mid;
        }
    }
    if (nums[start] === target) return start;
    if (nums[end] === target) return end;
    return -1;
};

var findLast = function(nums, target) {
    let start = 0;
    let end = nums.length - 1;
    while (start + 1 < end) {
        let mid = Math.floor(start + (end - start) / 2);
        if (nums[mid] > target) {
            end = mid;
        } else {
            start = mid;
        }
    }
    if (nums[end] === target) return end;
    if (nums[start] === target) return start;
    return -1;
};

相关推荐