当前位置:网站首页>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]
}
};
边栏推荐
- 可变长参数
- Indentation of tabs and spaces when writing programs for sublime text
- Deep learning: derivation of shallow neural networks and deep neural networks
- Deep anatomy of C language -- C language keywords
- China's high purity aluminum target market status and investment forecast report (2022 Edition)
- UnsupportedOperationException异常
- Synchronized solves problems caused by sharing
- Promise 在uniapp的简单使用
- Detailed explanation of heap sorting
- 深度剖析C语言指针
猜你喜欢

Current situation and trend of character animation

2022.02.13 - 238. Maximum number of "balloons"

PC easy to use essential software (used)

vb.net 随窗口改变,缩放控件大小以及保持相对位置

Target detection - pytorch uses mobilenet series (V1, V2, V3) to build yolov4 target detection platform

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
![Verrouillage [MySQL]](/img/ce/9f8089da60d9b3a3f92a5e4eebfc13.png)
Verrouillage [MySQL]

Deep analysis of C language pointer

Bottom up - physical layer

Computer cleaning, deleted system files
随机推荐
C语言深度解剖——C语言关键字
角色动画(Character Animation)的现状与趋势
sublime text没关闭其他运行就使用CTRL+b运行另外的程序问题
2022.02.13 - NC003. Design LRU cache structure
移位运算符
FairGuard游戏加固:游戏出海热潮下,游戏安全面临新挑战
Research Report on Market Research and investment strategy of microcrystalline graphite materials in China (2022 Edition)
Detailed explanation of heap sorting
Golang force buckle leetcode 1020 Number of enclaves
704 二分查找
marathon-envs项目环境配置(强化学习模仿参考动作)
查看局域网中电脑设备
超高效!Swagger-Yapi的秘密
Shift Operators
深度剖析C语言指针
【嵌入式】Cortex M4F DSP库
优秀的软件测试人员,都具备这些能力
[embedded] cortex m4f DSP Library
On the inverse order problem of 01 knapsack problem in one-dimensional state
Esp8266-rtos IOT development