当前位置:网站首页>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]
}
};
边栏推荐
- Precise query of tree tree
- Unified ordering background interface product description Chinese garbled
- sublime text中conda环境中plt.show无法弹出显示图片的问题
- sys. argv
- PLT in Matplotlib tight_ layout()
- JVM quick start
- [MySQL] database stored procedure and storage function clearance tutorial (full version)
- R language ggplot2 visualization, custom ggplot2 visualization image legend background color of legend
- FairGuard游戏加固:游戏出海热潮下,游戏安全面临新挑战
- Sublime text in CONDA environment plt Show cannot pop up the problem of displaying pictures
猜你喜欢
随机推荐
pytorch训练好的模型在加载和保存过程中的问题
【Nvidia开发板】常见问题集 (不定时更新)
Simple use of promise in uniapp
Guangzhou will promote the construction of a child friendly city, and will explore the establishment of a safe area 200 meters around the school
Variable length parameter
【嵌入式】使用JLINK RTT打印log
Esp8266-rtos IOT development
延迟初始化和密封类
China's high purity aluminum target market status and investment forecast report (2022 Edition)
sublime text中conda环境中plt.show无法弹出显示图片的问题
vb. Net changes with the window, scales the size of the control and maintains its relative position
Light of domestic games destroyed by cracking
egg. JS getting started navigation: installation, use and learning
个人电脑好用必备软件(使用过)
Chrome浏览器的crash问题
Verrouillage [MySQL]
Sort according to a number in a string in a column of CSV file
704 二分查找
China vanadium battery Market Research and future prospects report (2022 Edition)
ESP8266-RTOS物联网开发