当前位置:网站首页>给定一个整数数组nums和一个目标值target,在该数组中找出 和为 目标值的那两个整数,并返回他们的数组下标。
给定一个整数数组nums和一个目标值target,在该数组中找出 和为 目标值的那两个整数,并返回他们的数组下标。
2022-07-16 11:55:00 【不能懒鸭】
- 可以假设每种输入只有一种答案
- 例子 nums = [1,2,5] target=7 返回[1,2]
let arr1 = [1,2,4,6,7]
let target=3
- 暴力双层for循环
function twoSum1(nums,target){
let len = nums.length
for(let i=0;i<len;i++){
for(let j = i+1;j<len;j++){
if(nums[i]+ nums[j]===target){
return [i,j]
}
}
}
return []
}
console.log(twoSum1(arr1,target)) [0,1]
2.一层for循环+ map的 key值的唯一性
function twoSum2(nums,target){
let len = nums.length
let map = new Map()
for(let i =0;i<len;i++){
if(map.has(target-nums[i])){
return [map.get(target-nums[i]),i]
}
map.set(nums[i],i)
}
return []
}
console.log(twoSum2(arr1,target)) [0,1]
边栏推荐
- Rapport mondial sur le développement de l'industrie de l'enseignement professionnel 2022
- 爱立信以侵权为由要求禁售,苹果回返美国反诉,这一幕如此熟悉
- Introduction to leetcode special dynamic planning
- 数据湖基本架构
- 一 kernel编译系统概述
- 【实战】1382- 一文拥有属于你的 puppeteer 爬虫应用
- PostgreSQL source code (10) xlog assembly
- npm WARN config global `--global`, `--local` are deprecated. Use `--location=global` instead.
- Postgresql源码(7)Xlog格式
- [HMS core], [FAQ], [Health Kit] encountered some small problems in the process of integrating sports health services. Today, I share with you (Huawei watch, Bracelet + sports health service problems C
猜你喜欢
随机推荐
主进程 主线程和子线程 三者退出的关系
如何通过客户价值分析让银行收入倍增
Architecture layering of standard web system of Architecture Series
How to build a code server cloud ide platform on kubernetes
js base64转图片
C# 程序调试和异常处理(try catch)
面试官:为什么 Redis 要有哨兵?我该怎么回答?
二 配置目标make menuconfig的执行过程分析
From physics to AI and war database, the career choice of post-95 programmers
In the forced update of Huawei applications, occasionally click "exit application" to exit the application
[harmony OS] [FAQ] Hongmeng application development problem sharing (font / constructor)
关于cJSON的valueint超过整型范围的问题
Pytest+allure custom report
多米诺骨牌上演:三箭资本崩盘始末
Analysis of websocket hijacking
我回来了
【实战】1382- 一文拥有属于你的 puppeteer 爬虫应用
文件解析漏洞详解
面试官:Redis主从集群切换数据丢失问题如何应对?
An excellent graphical tool for information collection maltego









