当前位置:网站首页>从数组中找出和为目标的下标
从数组中找出和为目标的下标
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}
}
边栏推荐
- Leetcode basic programming: array
- Cannot activate CONDA virtual environment in vscode
- Let正版短信测压开源源码
- Federal learning: dividing non IID samples according to Dirichlet distribution
- 解析少儿编程中的动手搭建教程
- oracle 存储过程与job任务设置
- Mapping location after kotlin confusion
- 2022阿里巴巴全球数学竞赛 第4题 虎虎生威(盲盒问题、集卡问题)解决思路
- 案例分享|智慧化的西部机场
- 【ClickHouse】How to create index for Map Type Column or one key of it?
猜你喜欢
Getting started with pytest ----- confitest Application of PY
DC-1靶场搭建及渗透实战详细过程(DC靶场系列)
Here comes the chicken soup! Keep this quick guide for data analysts
Rhcsa --- work on the fourth day
[common error] the DDR type of FPGA device is selected incorrectly
win10 磁盘管理 压缩卷 无法启动问题
Idea automatic package import and automatic package deletion settings
Mysql表insert中文变?号的问题解决办法
C# 基于MQTTNet的服务端与客户端通信案例
June book news | 9 new books are listed, with a strong lineup and eyes closed!
随机推荐
Detailed process of DC-1 range construction and penetration practice (DC range Series)
10 minute quick start UI automation ----- puppeter
Cannot activate CONDA virtual environment in vscode
Online incremental migration of DM database
Embedded-c language-8-character pointer array / large program implementation
fastText文本分类
JS interview collection test question 1
解析少儿编程中的动手搭建教程
Common errors of dmrman offline backup
LM09丨费雪逆变换反转网格策略
Design and implementation of general interface open platform - (44) log processing of API services
Line by line explanation of yolox source code of anchor free series network (7) -- obj in head_ loss、Cls_ Loss and reg_ Calculation and reverse transmission of loss I
Embedded-c language-9-makefile/ structure / Consortium
06 装饰(Decorator)模式
Thinkphp內核工單系統源碼商業開源版 多用戶+多客服+短信+郵件通知
Starting from the classification of database, I understand the map database
TypeScript类的使用
Leetcode- insert and sort the linked list
How to modify data file path in DM database
DJB Hash