当前位置:网站首页>34. 在排序数组中查找元素的第一个和最后一个位置 ●●
34. 在排序数组中查找元素的第一个和最后一个位置 ●●
2022-06-11 10:38:00 【chenyfan_】
34. 在排序数组中查找元素的第一个和最后一个位置 ●●
描述
给定一个按照升序排列的整数数组 nums,和一个目标值 target。
找出给定目标值在数组中的开始位置和结束位置。
如果数组中不存在目标值 target,返回 [-1, -1]。
进阶:
你可以设计并实现时间复杂度为 O(log n) 的算法解决此问题吗?
示例
输入:nums = [5,7,7,8,8,10], target = 8
输出:[3,4]
题解
1. 暴力
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
// 1、遍历
int n = nums.size();
int left = -1; //左边界
int right = -1; //右边界
for ( int i = 0; i < n; ++i){
// 从左往右遍历
if (nums[i] == target){
if (left == -1){
left = i;
right = i;
}
else{
right = i;
}
}
}
return vector<int>{
left,right};
}
};
2. 二分查找
时间复杂度: O ( log n ) O(\log n) O(logn),其中 nn 为数组的长度。二分查找的时间复杂度为 O ( log n ) O(\log n) O(logn),一共会执行两次,因此总时间复杂度为 O ( log n ) O(\log n) O(logn)。
空间复杂度: O ( 1 ) O(1) O(1) 。只需要常数空间存放若干变量。
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
// 找到第一个等于或大于target的数
int left = 0, right = nums.size() - 1;
while(left <= right){
int mid = (left + right) >> 1;
if(nums[mid] >= target){
right = mid - 1;
}else{
left = mid + 1;
}
}
int start = right + 1;
// 找到最后一个小于或等于target的数
left = start, right = nums.size() - 1;
while(left <= right){
int mid = (left + right) >> 1;
if(nums[mid] <= target){
left = mid + 1; // left 为 找到第一个大于target的数
}else{
right = mid - 1;
}
}
int end = left - 1; // left - 1为最后一个小于或等于target的数
if (start <= end){
// left > right 不存在target
return vector<int> {
start, end};
}
return vector<int> {
-1, -1};
}
};
边栏推荐
- Ngui, chat scroll box, UI textlist
- 链接器和链接器选项、运行时库和运行时库设置、配置设置、生成过程和方法
- Wechat cloud development al short video one click face changing applet source code
- 使用 Hystrix 实现微服务的容错处理
- New Zealand is one of the best countries for road safety
- C语言校园导游咨询系统
- Ngui, select gender male and female
- 95后大厂程序员删库被判刑!只因项目被接手对领导心生不满
- MySQL下载安装使用-完整详细步骤
- 详解2.5G/5G/10G Base-T以太网接口物理层一致性测试!
猜你喜欢

NFT will change data ownership in the metauniverse

NFT 2.0: 下一代的NFT将是精简且值得信赖的NFT

Detail measurement of DC-DC and PDN with network analyzer

pyspark案例系列4-dataframe输出到单个文件夹的解决方案

PHP仿网易云原创音乐分享平台网站源码

Why is Web3 a game changer for the "creator economy"

Campus lost and found applet source code can be used for graduation design

Mn Monet pagoda host system v1.5 release

Use of kingbasees UDP monitoring tool for gold warehouse database

Leetcode 1995. 统计特殊四元组(暴力枚举)
随机推荐
MySQL下载安装使用-完整详细步骤
国际多语言出海商城返佣产品自动匹配订单源码
数字藏品系统开发源码搭建
【K-Means】K-Means学习实例
云画质助手iApp源码
MySQL基础篇常用约束总结上篇
NFT will change data ownership in the metauniverse
Beginning an excellent emlog theme
MN梦奈宝塔主机系统V1.5版本发布
Ngui, floating blood
NGUI,冷却效果
地铁路线图云开发小程序源码和配置教程
NGUI,飘血
&lt; Pytorch series 4 & gt;: Constructing neural network model
NGUI,背包拖拽,以及随机克隆图片知识点
NGUI,选择性别男女
Global pooling – pytoch
[games101] operation 2 -- triangle rasterization
Kingbasees create database objects in batch
Hardware Description Language HDL