当前位置:网站首页>从数组中找出和为目标的下标
从数组中找出和为目标的下标
2022-07-02 04:58:00 【Jimmy_jimi】
问题描述
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
解决方案:
这是选择hash表提高查找对应数字的方法,因为hashmap的查找复杂度为O(1).
为什么记录这个,是因为刚接触go,有两个比较觉得有意义的书写方式.
package main
import "fmt"
func twoSum(nums []int, target int) []int {
hashTable := map[int]int{
}
for i, x := range nums {
if p, ok := hashTable[target-x]; ok {
fmt.Println(p,i)
return []int{
p, i}
}
//hashmap中key为数值,value为对应的数组下标
//通过值去找想要的下标
hashTable[x] = i
}
return nil
}
func main() {
nums := []int{
1,2,3,4,5,10}
target := 11
twoSum(nums,target)
}
for i, x := range nums {
//检测映射中是否存在一个键值:target-x在映射hashTable的map中是否有值?
if p, ok := hashTable[target-x]; ok {
return []int{
p, i}
}
边栏推荐
- 面试会问的 Promise.all()
- Practical problem solving ability of steam Education
- Basic differences between Oracle and MySQL (entry level)
- Gin framework learning code
- C # picture display occupancy problem
- 奠定少儿编程成为基础学科的原理
- Video multiple effects production, fade in effect and border background are added at the same time
- Detailed process of DC-1 range construction and penetration practice (DC range Series)
- Mysql表insert中文变?号的问题解决办法
- Pit encountered in win11 pytorch GPU installation
猜你喜欢

数学知识(欧拉函数)

Mysql表insert中文变?号的问题解决办法

Thinkphp內核工單系統源碼商業開源版 多用戶+多客服+短信+郵件通知

Summary of database problems

Keil compilation code of CY7C68013A

How to configure PostgreSQL 12.9 to allow remote connections

Online incremental migration of DM database

培养中小学生对教育机器人的热爱之心

Pytest learning ----- pytest Interface Association framework encapsulation of interface automation testing

Express logistics quick query method, set the unsigned doc No. to refresh and query automatically
随机推荐
TypeScript函数详解
oracle 存储过程与job任务设置
How to configure PostgreSQL 12.9 to allow remote connections
Let正版短信测压开源源码
[bus interface] Axi interface
Knowledge arrangement about steam Education
Summary of MySQL key challenges (2)
Here comes the chicken soup! Keep this quick guide for data analysts
UNET deployment based on deepstream
Cubemx DMA notes
Learn what definitelytyped is through the typescript development environment of SAP ui5
数学知识(欧拉函数)
What are the rules and trading hours of agricultural futures contracts? How much is the handling fee deposit?
Keil compilation code of CY7C68013A
Idea automatic package import and automatic package deletion settings
ansible安装与使用
Pytest learning ----- pytest Interface Association framework encapsulation of interface automation testing
Summary of database problems
One step implementation of yolox helmet detection (combined with oak intelligent depth camera)
fastText文本分类