34. Find First and Last Position of Element in Sorted Array
题目
Given an array of integers nums 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].
给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。
你的算法时间复杂度必须是 O(log n) 级别。
如果数组中不存在目标值,返回 [-1, -1]。
Example
Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]
Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]
解法
暴力搜索时间复杂度不符合要求,使用二分法
- 先使用二分法找到target对应的left, mid, right
- 再从left-mid序列中找到第一个target,mid-right序列中找到最后一个target
代码
public int[] searchRange(int[] nums, int target) {
int[] res = {-1,-1};
int left = 0, right = nums.length-1;
int mid = -1;
while(left <= right) {
mid = (left+right) / 2;
if(target == nums[mid]) {
res[0] = mid;
res[1] = mid;
int ll = left, lr = mid-1, rl = mid+1, rr = right;
// 找左边序列的第一个target
while(ll <= lr) {
int m = (ll + lr) / 2;
if(target == nums[m]) {
res[0] = m;
lr = m - 1;
}
else // 左边序列均<=nums[m]
ll = m + 1;
}
// 找右边序列的最后一个target
while(rl <= rr) {
int m = (rl + rr) / 2;
if(target == nums[m]) {
res[1] = m;
rl = m + 1;
}
else // 右边序列均>=nums[m]
rr = m - 1;
}
break;
}
else if(target < nums[mid])
left = mid + 1;
else
right = mid - 1;
}
return res;
}
执行用时 : 7 ms, 在Find First and Last Position of Element in Sorted Array的Java提交中击败了71.14% 的用户
内存消耗 : 44.8 MB, 在Find First and Last Position of Element in Sorted Array的Java提交中击败了0.60% 的用户