LeetCode 34. Search for a Range
Description
Given an array of integers sorted in ascending order, find the starting and ending position of a given target value.
Your algorithm’s runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1].
For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].
题目大意为在一个有序数组中找到所给值在数组中的范围,题目要求算法的时间复杂度为(logn),因为数组是有序的所以我们可以使用二分查找来实现。
class Solution {
// 返回最左边或这最右边等于 target 的值在数组中的下标。
private int extremeInsertionIndex(int[] nums, int target, boolean left) {
int lo = 0;
int hi = nums.length;
while (lo < hi) {
int mid = (lo+hi)/2;
if (nums[mid] > target || (left && target == nums[mid])) {
hi = mid;
}
else {
lo = mid+1;
}
}
return lo;
}
public int[] searchRange(int[] nums, int target) {
int[] targetRange = {-1, -1};
int leftIdx = extremeInsertionIndex(nums, target, true);
// 断言 leftIdx 在数组范围内并且 target 在数组中
if (leftIdx == nums.length || nums[leftIdx] != target) {
return targetRange;
}
targetRange[0] = leftIdx;
targetRange[1] = extremeInsertionIndex(nums, target, false)-1;
return targetRange;
}
}
Complexity Analysis
Time complexity : O(lgn)
Because binary search cuts the search space roughly in half on each iteration, there can be at most rceil⌈lgn⌉ iterations. Binary search is invoked twice, so the overall complexity is logarithmic.
Space complexity : O(1)
All work is done in place, so the overall memory usage is constant.