当前位置:网站首页>从数组中找出和为目标的下标
从数组中找出和为目标的下标
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}
}
边栏推荐
- Markdown编辑语法
- Federal learning: dividing non IID samples according to Dirichlet distribution
- Starting from the classification of database, I understand the map database
- How do I interview for a successful software testing position? If you want to get a high salary, you must see the offer
- Mysql重点难题(2)汇总
- [common error] the DDR type of FPGA device is selected incorrectly
- Pytest learning ----- pytest Interface Association framework encapsulation of interface automation testing
- Research on the security of ognl and El expressions and memory horse
- June book news | 9 new books are listed, with a strong lineup and eyes closed!
- 農業生態領域智能機器人的應用
猜你喜欢

Video cover image setting, put cover images into multiple videos in the simplest way

Social media search engine optimization and its importance

UNET deployment based on deepstream

Win10 disk management compressed volume cannot be started

AcrelEMS高速公路微电网能效管理平台与智能照明解决方案智慧点亮隧道

面试会问的 Promise.all()
![[bus interface] Axi interface](/img/ee/95ade7811ec2c37fb67a77f0b6ae2a.jpg)
[bus interface] Axi interface

DMA Porter

Change deepin to Alibaba image source
![Learn AI safety monitoring project from zero [attach detailed code]](/img/a9/cb93f349229e86cbb05ad196ae9553.jpg)
Learn AI safety monitoring project from zero [attach detailed code]
随机推荐
Here comes the chicken soup! Keep this quick guide for data analysts
Embedded-c language-9-makefile/ structure / Consortium
Lay the foundation for children's programming to become a basic discipline
6.30 year end summary, end of student age
C case of communication between server and client based on mqttnet
Online incremental migration of DM database
UNET deployment based on deepstream
農業生態領域智能機器人的應用
C# 基于MQTTNet的服务端与客户端通信案例
Use of typescript classes
Analyzing the hands-on building tutorial in children's programming
Leetcode- insert and sort the linked list
数学问题(数论)试除法做质数的判断、分解质因数,筛质数
Let genuine SMS pressure measurement open source code
Application d'un robot intelligent dans le domaine de l'agroécologie
Oracle stored procedure and job task setting
js面试收藏试题1
Domestic all Chinese automatic test software apifox
正大美欧4的主账户关注什么数据?
Mouse events in JS