当前位置:网站首页>js查找数组下标
js查找数组下标
2022-04-22 00:33:00 【马德里甜欣】
题目:
给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target ,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。
方法1:递归
思路:先找到中间位置,判断是否是需要寻找的目标值,如果是就返回,不是的话判断目标值和中间元素的大小,然后继续向左右子树递归寻找
复杂度:时间复杂度O(logn),空间复杂度O(logn),递归栈大小
方法2:非递归
思路:定义left、right指针,比较目标元素和中间元素的大小,然后不断缩小左右指针的范围继续寻找目标元素
复杂度:时间复杂度O(logn),空间复杂度O(1)
此处使用方法二
/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var search = function (nums, target) {
var left = 0, right = nums.length - 1
while (left <= right) {
var mid = (left + right) >> 1;
if (nums[mid] > target) {
right = mid - 1
}
if (nums[mid] === target) return mid;
if (nums[mid] < target) {
left = mid + 1
}
}
return -1
};
示例1
输入:
[-1,0,3,4,6,10,13,14],13
返回值:
6
说明:
13 出现在nums中并且下标为 6
示例2
输入:
[],3
返回值:
-1
说明:
nums为空,返回-1
示例3
输入:
[-1,0,3,4,6,10,13,14],2
返回值:
-1
说明:
2 不存在nums中因此返回 -1
版权声明
本文为[马德里甜欣]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_51564923/article/details/124318730
边栏推荐
- Redis has three modes - master-slave replication, sentinel mode and cluster
- 解决Svelte项目使用pnpm后Prettier无效问题
- [知识图谱] Tushare数据获取和展示(1/*)
- Muduo project introduction
- Click, walk and move of characters in 3D sandbox game
- hex,base64,urlencode编码方案对比
- R语言广义线性模型GLM:线性最小二乘、对数变换、泊松、二项式逻辑回归分析冰淇淋销售时间序列数据和模拟
- See how the project manager brings a project to ruin
- How should the old computer reinstall the system
- 诚邀报名丨首期OpenHarmony开发者成长计划分享日
猜你喜欢

智汀如何连接华为智能音箱?

Apachecon Asia 2022 speech collection begins!

【ACM/webank】#491. Incremental subsequence (use HashSet to record and prevent repeated subsequences)

在setTimeout里设置倒数5秒计时的方法

【Zeele_Tech】ROS/ROS 2介绍

Oceanbase 和 TiDB 粗浅对比之 - 执行计划

云原生爱好者周刊:寻找 Netlify 开源替代品

MySQL basic collection
![[course summary] Hello harmonyos series of courses, take you to zero foundation introduction](/img/47/902a1a76991217dff0a89ee944a8d1.jpg)
[course summary] Hello harmonyos series of courses, take you to zero foundation introduction

No more simple intention lock
随机推荐
Huawei has launched the new BMW 7 Series in the application market to create a luxury peak smart travel experience
Basic operation of redis transaction
2022 年 4 月中国数据库排行榜:春风拂面春意暖,分数回升四月天
为什么Web端登录需要验证码?
13 bullish forms of K-line chart (Part 2)
Rpcx source code learning - server side
It is recommended to provide outline - one click expansion function
logstash导入movielens测试数据
云原生爱好者周刊:寻找 Netlify 开源替代品
hex,base64,urlencode编码方案对比
BI工具如何选型?这3个问题是关键!
Introduction to Haskell monoid
Muduo project introduction
Solve the problem that prettier is invalid after svelte project uses pnpm
How to set the validity period of win11 account password? Win11 account password usage period setting tutorial
Under the catalysis of the epidemic, why can this product promote the commercialization of automatic distribution?
Why does the web login need a verification code?
【Zeele_Tech】ROS/ROS 2介绍
Yijingjie database will receive Chinese software investment of no more than 389 million yuan
数字化时代,企业运维面临现状及挑战分析解读