We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
给定一个按照升序排列的整数数组 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]
提示:
The text was updated successfully, but these errors were encountered:
复杂度 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]; };
Sorry, something went wrong.
复杂度 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; }
No branches or pull requests
34. 在排序数组中查找元素的第一个和最后一个位置
给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。
如果数组中不存在目标值 target,返回 [-1, -1]。
进阶:
示例 1:
示例 2:
示例 3:
提示:
The text was updated successfully, but these errors were encountered: