leetcode打码记录
34. 在排序数组中查找元素的第一个和最后一个位置
给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。
你的算法时间复杂度必须是 O(log n) 级别。
如果数组中不存在目标值,返回 [-1, -1]。
示例 1:
输入: nums = [5,7,7,8,8,10], target = 8
输出: [3,4]
示例 2:
输入: nums = [5,7,7,8,8,10], target = 6
输出: [-1,-1]
解题思路
时间复杂度必须是 O(log n) 级别,因此采用二分法搜索数组。由于要搜索target出现的开始和结束位置,不能通过二分法一次搜索出来。对此需要分别搜索target的开始和结束位置。
代码
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
vector<int> res;
if(nums.size()==0){
res.push_back(-1);
res.push_back(-1);
return res;
}
int head_i = 0;
int head_j = nums.size() - 1;
int tail_i = 0;
int tail_j = nums.size() - 1;
int head = -1;
int tail = -1;
if(nums[0]==target){
head = 0;
}
if(nums[tail_j]==target){
tail = tail_j;
}
while(head_i<head_j || tail_i<tail_j){
// 搜索开始位置
if(head_i < head_j){
int n = (head_i + head_j)/2;
if(nums[n]==target){
if(n==head_i || nums[n-1]<target){
head = n;
head_i = head_j;
}
else{
head_j = n;
}
}
else{
if(nums[n]>target){
head_j = n;
}
else{
head_i = n;
}
}
if(head_i == head_j-1){
head_i = head_j;
}
}
// 搜索结束位置
if(tail_i<tail_j){
int n = (tail_i + tail_j)/2;
if(nums[n]==target){
if(n==tail_j || nums[n+1]>target){
tail = n;
tail_i = tail_j;
}
else{
tail_i = n;
}
}
else{
if(nums[n]>target){
tail_j = n;
}
else{
tail_i = n;
}
}
if(tail_i == tail_j-1){
tail_i = tail_j;
}
}
}
if(head==-1 && tail!=-1){
res.push_back(tail);
res.push_back(tail);
}
else{
if(tail==-1 && head!=-1){
res.push_back(head);
res.push_back(head);
}
else{
res.push_back(head);
res.push_back(tail);
}
}
return res;
}
};