当前位置:网站首页>LeetCode:34. 在排序数组中查找元素的第一个和最后一个位置
LeetCode:34. 在排序数组中查找元素的第一个和最后一个位置
2022-07-06 08:44:00 【Bertil】
给定一个按照升序排列的整数数组 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 <= 10^5
- -10^9 <= nums[i] <= 10^9
- nums 是一个非递减数组
- -10^9 <= target <= 10^9
解题思路
1.首先判断数组非空且存在此元素,然后用indexOf和lastIndexOf方法来查找元素的第一个和最后一个位置
代码
/** * @param {number[]} nums * @param {number} target * @return {number[]} */
var searchRange = function(nums, target) {
if(nums !== [] && nums.indexOf(target) !== -1) {
let left = nums.indexOf(target)
let right = nums.lastIndexOf(target)
return [left, right]
}else {
return [-1, -1]
}
};
边栏推荐
- [MySQL] database stored procedure and storage function clearance tutorial (full version)
- swagger设置字段required必填
- Deep analysis of C language pointer
- egg. JS getting started navigation: installation, use and learning
- Delay initialization and sealing classes
- Using pkgbuild:: find in R language_ Rtools check whether rtools is available and use sys The which function checks whether make exists, installs it if not, and binds R and rtools with the writelines
- Generator parameters incoming parameters
- TCP/IP协议
- Synchronized solves problems caused by sharing
- 有效提高软件产品质量,就找第三方软件测评机构
猜你喜欢

Unified ordering background interface product description Chinese garbled

Delay initialization and sealing classes

优秀的软件测试人员,都具备这些能力

After PCD is converted to ply, it cannot be opened in meshlab, prompting error details: ignored EOF

Precise query of tree tree

深度剖析C语言数据在内存中的存储

JS native implementation shuttle box

Variable length parameter

sublime text没关闭其他运行就使用CTRL+b运行另外的程序问题

电脑清理,删除的系统文件
随机推荐
MySQL learning records 12jdbc operation transactions
hutool优雅解析URL链接并获取参数
Tcp/ip protocol
The ECU of 21 Audi q5l 45tfsi brushes is upgraded to master special adjustment, and the horsepower is safely and stably increased to 305 horsepower
2022.02.13 - NC001. Reverse linked list
查看局域网中电脑设备
Detailed explanation of heap sorting
Purpose of computer F1-F12
[NVIDIA development board] FAQ (updated from time to time)
Synchronized solves problems caused by sharing
TDengine 社区问题双周精选 | 第三期
C語言雙指針——經典題型
POI add write excel file
ROS编译 调用第三方动态库(xxx.so)
Light of domestic games destroyed by cracking
China high purity silver nitrate Market Research and investment strategy report (2022 Edition)
Image, CV2 read the conversion and size resize change of numpy array of pictures
Bottom up - physical layer
How to conduct interface test? What are the precautions? Nanny level interpretation
China dihydrolaurenol market forecast and investment strategy report (2022 Edition)