1 问题
问题描述(原文):
Given an array of integers nums
sorted in ascending order, find the starting and ending position of a given target
value.
If target
is not found in the array, return [-1, -1]
.
You must write an algorithm with O(log n)
runtime complexity.
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]
Example 3:
Input: nums = [], target = 0
Output: [-1,-1]
Constraints:
- 0 <= nums.length <= 105
- -109 <= nums[i] <= 109
- nums is a non-decreasing array.
- -109 <= target <= 109
2 分析:
给一个升序的数组 nums[]
和一个数 target
, 要求返回数组中值为 target
的元素的 下标范围, 若 nums[]
中没有值为 target
的元素, 则返回 {-1,-1}
.
要求时间复杂度为 O(log n)
.
看到 O(log n)
自然最先想到 二分查找.
可以先通过 二分查找 在数组 nums[] 中找到 target;
如果找不到返回 {-1, -1};
如果能找到, 则在此下标前后两个方向分别再次用 二分查找 找 起始下标 和 终止下标.
class Solution {
public int[] searchRange(int[] nums, int target) {
if (nums == null || nums.length == 0) {
return new int[]{-1, -1};
}
int start = 0, end = nums.length - 1;
// 起始下标 r1, 终止下标 r2
int r1 = -1, r2 = -1;
while (start <= end) {
int mid = (start + end) / 2;
if (nums[mid] == target) {
r1 = findFirst(nums, start, end, target);
r2 = findEnd(nums, start, end, target);
break;
} else if (nums[mid] < target) {
start = mid + 1;
} else {
end = mid - 1;
}
}
return new int[]{r1, r2};
}
private int findFirst(int[] nums, int start, int end, int target) {
int s = start, e = end;
while (s != e) {
int mid = (s + e) / 2;
if (nums[mid] == target) {
if (mid - 1 < start || nums[mid - 1] < target) {
return mid;
} else {
e = mid - 1;
}
} else {
s = mid + 1;
}
}
return s;
}
private int findEnd(int[] nums, int start, int end, int target) {
int s = start, e = end;
while (s != e) {
int mid = (s + e) / 2;
if (nums[mid] == target) {
if (mid + 1 > end || nums[mid + 1] > target) {
return mid;
} else {
s = mid + 1;
}
} else {
e = mid - 1;
}
}
return s;
}
}
3 结果:
虽然这题在 LeetCode 是 medium 难度的题, 但只考察了基础算法 二分查找, 其实还是很容易做出来的.