难度系数: 中等
给你一个按照非递减顺序排列的整数数组 nums,和一个目标值 target。请你找出给定目标值在数组中的开始位置和结束位置。
如果数组中不存在目标值 target,返回 [-1, -1]。
你必须设计并实现时间复杂度为 O(logn) 的算法解决此问题。
示例 1:
1 2
| 输入:nums = [5,7,7,8,8,10], target = 8 输出:[3,4]
|
示例 2:
1 2
| 输入:nums = [5,7,7,8,8,10], target = 6 输出:[-1,-1]
|
示例 3:
1 2
| 输入:nums = [], target = 0 输出:[-1,-1]
|
提示:
- 0 <= nums.length <= 105
- −109 <= nums[i] <= 109
- nums 是一个非递减数组
- −109 <= target <= 109
解法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| class Solution { public int[] searchRange(int[] nums, int target) { int[] result = new int[]{-1, -1}; int length = nums.length; if (nums.length == 0) { return result; } if (nums.length == 1) { if (nums[0] == target) { result[0] = 0; result[1] = 0; } return result; } int left = 0; int right = length - 1; int middle; while(left <= right) { middle = (left + right) / 2; if (nums[middle] < target) { left = middle + 1; } else { right = middle - 1; } } if (left >= 0 && left <= length -1 && nums[left] == target) { result[0] = left; } left = 0; right = length - 1; while(left <= right) { middle = (left + right) / 2; if (nums[middle] > target) { right = middle - 1; } else { left = middle + 1; } } if (right >= 0 && right <= length - 1 && nums[right] == target) { result[1] = right; } return result; } }
|
官方解法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| class Solution { public int[] searchRange(int[] nums, int target) { int leftIdx = binarySearch(nums, target, true); int rightIdx = binarySearch(nums, target, false) - 1; if (leftIdx <= rightIdx && rightIdx < nums.length && nums[leftIdx] == target && nums[rightIdx] == target) { return new int[]{leftIdx, rightIdx}; } return new int[]{-1, -1}; }
public int binarySearch(int[] nums, int target, boolean lower) { int left = 0, right = nums.length - 1, ans = nums.length; while (left <= right) { int mid = (left + right) / 2; if (nums[mid] > target || (lower && nums[mid] >= target)) { right = mid - 1; ans = mid; } else { left = mid + 1; } } return ans; } }
|
原题链接:https://leetcode.cn/problems/find-first-and-last-position-of-element-in-sorted-array/