题目
给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。
如果数组中不存在目标值 target,返回 [-1, -1]。
进阶:
你可以设计并实现时间复杂度为 O(log n) 的算法解决此问题吗?
示例
输入:nums = [5,7,7,8,8,10], target = 8
输出:[3,4]
输入:nums = [5,7,7,8,8,10], target = 6
输出:[-1,-1]
输入:nums = [], target = 0
输出:[-1,-1]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
方法1:二分查找
Java实现
class Solution {
public int[] searchRange(int[] nums, int target) {
int n = nums.length;
int[] res = new int[]{-1, -1};
if (n == 0) return res;
int l = 0, r = n - 1;
while (l < r) {
int mid = l + r >> 1;
if (nums[mid] >= target) {
r = mid;
} else {
l = mid + 1;
}
}
if (nums[l] != target) return res;
res[0] = l;
l = 0;
r = n - 1;
while (l < r) {
int mid = l + r + 1 >> 1;
if (nums[mid] <= target) {
l = mid;
} else {
r = mid - 1;
}
}
res[1] = l;
return res;
}
}
方法2:模拟
Java实现
class Solution {
public int[] searchRange(int[] nums, int target) {
int n = nums.length;
int l = 0, r = n - 1;
int[] res = new int[]{-1, -1};
if (n == 1 && nums[0] != target) return res;
while (l < r && (nums[l] != target || nums[r] != target)) {
if (nums[l] != target) l++;
if (nums[r] != target) r--;
}
if (l <= r && nums[l] == target && nums[r] == target) {
res[0] = l;
res[1] = r;
}
return res;
}
}