当前位置:网站首页>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;
}
}
边栏推荐
- C语言去除字符串尾部的换行(或其他字符)
- Docker实战 -- 部署Redis集群与部署微服务项目
- 聚焦智慧城市,华为携手中科星图共同开拓数字化新蓝海
- Jour 13 Projet de santé mentale - chapitre 13
- 百度URL参数之LINK?URL参数加密解密研究(代码实例)
- Leetcode topic resolution remove nth node from end of list
- Home address exchange
- (1) Basic learning - Common shortcut commands of vim editor
- 解读创客教育中的团结协作精神
- 记一次GLIB2.14升级GLIB2.18的记录以及其中的步骤原理
猜你喜欢

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

Day_05 传智健康项目-预约管理-预约设置

Redis sentry

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

Day_ 04 smart health project - appointment management - package management

【Leetcode】431. Encode n-ary tree to binary tree (difficult)

聚焦智慧城市,华为携手中科星图共同开拓数字化新蓝海

图解 Google V8 # 17:消息队列:V8是怎么实现回调函数的?

Progress of layer 2 technical scheme

Summary of business logic security ideas
随机推荐
Link of Baidu URL Parameters? Recherche sur le chiffrement et le décryptage des paramètres d'URL (exemple de Code)
Index - MySQL
什么是客户体验自动化?
11、 Realization of textile fabric off shelf function
Simple about fastdfs
haas506 2.0开发教程-高级组件库-modem.net(仅支持2.2以上版本)
Day_12 传智健康项目-JasperReports
qt creater搭建osgearth环境(osgQT MSVC2017)
ffplay实现自定义输入流播放
Synchronous switching power supply reduces EMI layout dv/dt di/dt
Functions and basic structure of CPU
Difference between MySQL read committed and repeatability
Day_ 03 smart communication health project - appointment management - inspection team management
Leetcode topic resolution remove nth node from end of list
Word pattern for leetcode topic analysis
华为软件测试笔试真题之变态逻辑推理题
Illustration Google V8 18: asynchronous programming (I): how does V8 implement micro tasks?
js创建数组(元素都是对象)
Learning Tai Chi Maker - esp8226 (11) distribution network with WiFi manager Library
Summary of business logic security ideas