当前位置:网站首页>从数组中找出和为目标的下标
从数组中找出和为目标的下标
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}
}
边栏推荐
- Orthogonal test method and function diagram method for test case design
- Embedded-c language-8-character pointer array / large program implementation
- List of common bugs in software testing
- Leetcode basic programming: array
- Super detailed pycharm tutorial
- Domestic all Chinese automatic test software apifox
- Go GC garbage collection notes (three color mark)
- Embedded-c language-9-makefile/ structure / Consortium
- Basic differences between Oracle and MySQL (entry level)
- Here comes the chicken soup! Keep this quick guide for data analysts
猜你喜欢

Cultivate primary and secondary school students' love for educational robots

Interview question: do you know the difference between deep copy and shallow copy? What is a reference copy?

Pit encountered in win11 pytorch GPU installation

Practical problem solving ability of steam Education

Orthogonal test method and function diagram method for test case design

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

Let genuine SMS pressure measurement open source code

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

Summary of common string processing functions in C language

正大留4的主账户信息汇总
随机推荐
关于Steam 教育的知识整理
How to recover deleted data in disk
Lay the foundation for children's programming to become a basic discipline
Getting started with pytest ----- confitest Application of PY
I sorted out some basic questions about opencv AI kit.
Practical problem solving ability of steam Education
fastText文本分类
Express logistics quick query method, set the unsigned doc No. to refresh and query automatically
Mysql重点难题(2)汇总
[high speed bus] Introduction to jesd204b
Cache consistency solution - how to ensure the consistency between the cache and the data in the database when changing data
Unity particle Foundation
Ansible installation and use
Application of intelligent robot in agricultural ecology
Summary of main account information of zhengdaliu 4
Introduction to Luogu 3 [circular structure] problem list solution
CubeMx DMA笔记
Case sharing | intelligent Western Airport
6.30 year end summary, end of student age
DMA Porter