标签:off 时间 面试 查找 排序 offer else galaxy ==
给定一个按照升序排列的整数数组 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]
本题同【剑指Offer】面试题53 - I. 在排序数组中查找数字 I
时间复杂度:O(logn)
空间复杂度:O(1)
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
if (nums.empty()) return {-1, -1};
int left = searchLeft(nums, target);
int right = searchRight(nums, target);
return {left, right};
}
int searchLeft(vector<int> &nums, int target) {
int left = 0, right = nums.size() - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target) {
if (mid == 0 || (mid - 1 >= 0 && nums[mid - 1] != target)) {
return mid;
}
right = mid - 1;
} else if (nums[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
int searchRight(vector<int> &nums, int target) {
int left = 0, right = nums.size() - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target) {
if (mid == nums.size() - 1 || (mid + 1 <= nums.size() - 1 && nums[mid + 1] != target)) {
return mid;
}
left = mid + 1;
} else if (nums[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
};
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
if (nums.empty()) return {-1, -1};
int left = searchLeft(nums, target);
int right = searchRight(nums, target);
return {left, right};
}
int searchLeft(vector<int> &nums, int target) {
int left = 0, right = nums.size() - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target) {
//一直向左找
while (mid - 1 >= 0 && nums[mid - 1] == target) {
--mid;
}
return mid;
} else if (nums[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
int searchRight(vector<int> &nums, int target) {
int left = 0, right = nums.size() - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target) {
//一直向右找
while (mid + 1 <= nums.size() - 1 && nums[mid + 1] == target) {
++mid;
}
return mid;
} else if (nums[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
};
lower_bound:返回一个迭代器,指向键值 >= key的第一个元素
upper_bound:返回一个迭代器,指向键值 > key的第一个元素
时间复杂度:O(logn)
空间复杂度:O(1)
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
if (nums.empty()) return {-1, -1};
auto left = lower_bound(nums.begin(), nums.end(), target);
auto right = upper_bound(nums.begin(), nums.end(), target);
if (left == right) return {-1, -1};
return {left - nums.begin(), right - nums.begin() - 1};
}
};
【LeetCode】34. 在排序数组中查找元素的第一个和最后一个位置
标签:off 时间 面试 查找 排序 offer else galaxy ==
原文地址:https://www.cnblogs.com/galaxy-hao/p/12669640.html