当前位置:网站首页>Topic35——34. 在排序数组中查找元素的第一个和最后一个位置
Topic35——34. 在排序数组中查找元素的第一个和最后一个位置
2022-06-23 05:13:00 【_卷心菜_】
题目:给你一个按照非递减顺序排列的整数数组 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]
提示:
0 <= nums.length <= 105
-109 <= nums[i] <= 109
nums 是一个非递减数组
-109 <= target <= 109
class Solution {
public int[] searchRange(int[] nums, int target) {
int[] res = new int[2];
Arrays.fill(res, -1);
if(nums.length == 0)
return res;
int l = 0;
int r = nums.length;
// 寻找左侧边界
while(l < r) {
int mid = (l + r) / 2;
if(nums[mid] == target) {
r = mid;
} else if (nums[mid] > target) {
r = mid;
} else if (nums[mid] < target) {
l = mid + 1;
}
if(l >= r && l <= nums.length - 1 && nums[l] == target) {
res[0] = l;
}
}
l = 0;
r = nums.length;
// 寻找右侧边界
while(l < r) {
int mid = (l + r) / 2;
if(nums[mid] == target) {
l = mid + 1;
} else if (nums[mid] > target) {
r = mid;
} else if (nums[mid] < target) {
l = mid + 1;
}
if(l >= r && l - 1 >= 0 && nums[l - 1] == target) {
res[1] = l - 1;
}
}
return res;
}
}
边栏推荐
- Docker实战 -- 部署Redis集群与部署微服务项目
- bootstrap如何清除浮动的样式
- 索引——MySQL
- MySQL5.6 (5.7-8) 基于shardingsphere5.1.1 Sharding-Proxy模式读写分离
- Network packet capturing tcpdump User Guide
- Day_08 传智健康项目-移动端开发-体检预约
- Day_ 13 smart health project - Chapter 13
- minio单节点部署 minio分布式部署 傻瓜式部署过程 (一)
- Xray linkage crawlergo automatic scanning pit climbing record
- Termux
猜你喜欢

Steam教育对国内大学生的影响力

Day_12 传智健康项目-JasperReports

Day_ 05 smart communication health project - appointment management - appointment settings

【接口自动化】软件测试涨薪核心技能、让薪资涨幅200%

C # database reports errors. Let's have a look

vs+qt项目转qt creator

C# wpf 附加属性实现界面上定义装饰器

射频内容学习

图解 Google V8 # 18 :异步编程(一):V8是如何实现微任务的?

Day_ 11 smart communication health project - graphic report and poi Report
随机推荐
2020 smart power plant industry insight white paper
聚焦智慧城市,华为携手中科星图共同开拓数字化新蓝海
RF content learning
Design scheme of Small PLC based on t5l1
Illuminate\support\collection de duplication unique list de duplication
C Advanced Learning -- Reflection
索引——MySQL
qt creater搭建osgearth环境(osgQT MSVC2017)
A review: neural oscillation and brain stimulation in Alzheimer's disease
Day_ 10 smart health project - permission control, graphic report
Introduction to JVM principle
Given a node of a binary tree, return the successor node of the node
C语言去除字符串尾部的换行(或其他字符)
There are so many code comments! I laughed
Remove duplicates from sorted list II of leetcode topic resolution
Test of ers function under the supplier consignment purchase mode of SAP mm
【接口自动化】软件测试涨薪核心技能、让薪资涨幅200%
Tencent security 2021 report white paper collection (download attached)
phpStudy设置301重定向
C语言 踩坑:文档编码错误,导致base64中文编码错误