34. 在排序数组中查找元素的第一个和最后一个位置(Leetcode刷题笔记)
欢迎大家访问我的GitHub博客
https://lunan0320.github.io/
题目
给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。
如果数组中不存在目标值 target,返回 [-1, -1]。
进阶:
你可以设计并实现时间复杂度为 O(log n) 的算法解决此问题吗?
示例 1:
输入:nums = [5,7,7,8,8,10], target = 8
输出:[3,4]
示例 2:
输入:nums = [5,7,7,8,8,10], target = 6
输出:[-1,-1]
示例 3:
输入:nums = [], target = 0
输出:[-1,-1]
解题代码 C++(核心代码)
此处给出的是Leetcode的核心代码
本题重点是理解题目意思,需要找左、右边界
找到与target相等的之后,是收缩左边界还是右边界是重点!
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
vector<int>res;
res.push_back(getLeftIndex(nums, target));
res.push_back(getRightIndex(nums, target));
return res;
}
int getLeftIndex(vector<int>& nums, int target){
int left = 0;
int right = nums.size()-1;
int mid;
while (left <= right){
mid = left+((right-left) / 2);
if (nums[mid] < target) left = mid + 1;
else if (nums[mid] > target) right = mid - 1;
//找左边界的时候,遇到相等的需要收缩右边界
else right = mid - 1;
}
if (left >= nums.size() || nums[left] != target) return -1;
return left;
}
int getRightIndex(vector<int>& nums, int target){
int left = 0;
int right = nums.size()-1;
int mid;
while (left <= right){
mid = left+((right-left) / 2);
if (nums[mid] < target) left = mid + 1;
else if (nums[mid] > target) right = mid - 1;
//找右边界的时候,遇到相等的需要收缩左边界
else left = mid + 1;
}
if (right >= nums.size() || nums[right] != target) return -1;
return right;
}
};
解题代码 C++(本地运行)
此处给出的是在本地编译运行的代码,是对leetcode的补充
可以在本地直接运行
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
vector<int>res;
res.push_back(getLeftIndex(nums, target));
res.push_back(getRightIndex(nums, target));
return res;
}
int getLeftIndex(vector<int>& nums, int target) {
int left = 0;
int right = nums.size() - 1;
int mid;
while (left <= right) {
mid = left + ((right - left) / 2);
if (nums[mid] < target) left = mid + 1;
else if (nums[mid] > target) right = mid - 1;
//找左边界的时候,遇到相等的需要收缩右边界
else right = mid - 1;
}
if (left >= nums.size() || nums[left] != target) return -1;
return left;
}
int getRightIndex(vector<int>& nums, int target) {
int left = 0;
int right = nums.size() - 1;
int mid;
while (left <= right) {
mid = left + ((right - left) / 2);
if (nums[mid] < target) left = mid + 1;
else if (nums[mid] > target) right = mid - 1;
//找右边界的时候,遇到相等的需要收缩左边界
else left = mid + 1;
}
if (right >= nums.size() || nums[right] != target) return -1;
return right;
}
void print_vector(vector<int>& nums) {
int length = nums.size();
for (int i = 0; i < length; i++) {
cout << nums[i] << " ";
}
cout << endl;
}
};
int main() {
Solution solution;
vector<int> nums = { 5,7,7,8,8,10 };
int target;
cout << "请输入要查找的元素:" << endl;
cin >> target;
vector<int> res = solution.searchRange(nums, target);
solution.print_vector(res);
return 0;
}
算法效率
执行用时: 4 ms , 在所有 C++ 提交中击败了94.73% 的用户
内存消耗:13.2 MB , 在所有 C++ 提交中击败了 85.75% 的用户