当前位置:网站首页>Leetcode T34: 在排序数组中查找元素的第一个和最后一个位置
Leetcode T34: 在排序数组中查找元素的第一个和最后一个位置
2022-07-01 08:08: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]
思路
要满足 O ( log n ) O(\log n) O(logn) 的复杂度,要使用二分查找。
可以找到(target-0.5)的位置,代表target的开始位置;
通过找到(target+0.5)的位置,找到target的结束位置。
但是,要注意边界情况。例如:
nums = [5,7,7,8,8,10], target = 8
如果要找到7.5的下标 i n d l ind_l indl,那么得到下标3;如果要找到8.5的下标 i n d r ind_r indr,那么得到下标5,所以要加上一下操作:
如果 n u m s [ i n d l ] < t a r g e t nums[ind_l]<target nums[indl]<target, 那么 i n d l + + ind_l++ indl++
如果 n u m s [ i n d l ] > t a r g e t nums[ind_l]>target nums[indl]>target, 那么 i n d l − − ind_l-- indl−−
代码
int findInd(int[] nums, double target) {
int l = 0, r = nums.length-1;
while(l < r) {
int mid = (l+r) / 2;
int t = nums[mid];
if(t == target) {
return mid;
} else if (t < target){
l = mid+1;
} else {
r = mid-1;
}
}
return l;
}
public int[] searchRange(int[] nums, int target) {
if(nums.length == 0) {
int[] t = {
-1, -1};
return t;
}
int[] res = new int[2];
res[0] = findInd(nums, target-0.5);
res[1] = findInd(nums, target+0.5);
if(nums[res[0]] < target) res[0]+=1;
if(nums[res[1]] > target) res[1]--;
if(res[0] > res[1]) {
res[0] = -1;
res[1] = -1;
}
return res;
}
边栏推荐
- How to troubleshoot SharePoint online map network drive failure?
- SharePoint - how to quickly check whether SharePoint is standard or enterprise edition?
- php laravel微信支付
- Connect timed out of database connection
- Serial port oscilloscope software ns-scope
- [getting started] intercepting strings
- Airsim雷达相机融合生成彩色点云
- web254
- Gru of RNN
- 【入门】取近似值
猜你喜欢

Hijacking a user's browser with beef

Teach you how to apply for domestic trademark online step by step

On several key issues of digital transformation

【批处理DOS-CMD命令-汇总和小结】-Cmd窗口中常用操作符(<、<<、&<、>、>>、&>、&、&&、||、|、()、;、@)

Practice and Thinking on the architecture of a set of 100000 TPS im integrated message system

CPU设计实战-第四章实践任务一简单CPU参考设计调试

谈谈数字化转型的几个关键问题

【入门】截取字符串

Aardio - 阴影渐变文字

【入门】输入整型数组和排序标识,对其元素按照升序或降序进行排序
随机推荐
Airsim radar camera fusion to generate color point cloud
一套十万级TPS的IM综合消息系统的架构实践与思考
[introduction] approximate value
【力扣10天SQL入门】Day10 控制流
Aardio - 阴影渐变文字
The Windows C disk is full
Why some people earn nearly 10billion a year, while others earn 3000 a month: the details you ignore actually make the most money
web254
[untitled]
ContentType所有类型对比
postgresql源码学习(26)—— Windows vscode远程调试Linux上的postgresql
php laravel微信支付
源代码加密的意义和措施
P4 installation bmv2 detailed tutorial
On June 30, 2022, the record of provincial competition + national competition of Bluebridge
Access报表实现小计功能
力扣每日一题-第32天-1822.数组元素积的符号
SQL number injection and character injection
web254
Gdip - hatchbrush pattern table