当前位置:网站首页>从数组中找出和为目标的下标
从数组中找出和为目标的下标
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}
}
边栏推荐
- 6.30 year end summary, end of student age
- Oracle和MySQL的基本区别(入门级)
- [Yu Yue education] autumn 2021 reference materials of Tongji University
- JS interview collection test question 1
- cs架构下抓包的几种方法
- 案例分享|智慧化的西部机场
- Starting from the classification of database, I understand the map database
- Cubemx DMA notes
- Fasttext text text classification
- fastText文本分类
猜你喜欢

数学知识——快速幂的理解及例题

Cannot activate CONDA virtual environment in vscode

数学知识(欧拉函数)

Gin framework learning code

数学问题(数论)试除法做质数的判断、分解质因数,筛质数

Leetcode- insert and sort the linked list
![[high speed bus] Introduction to jesd204b](/img/78/1a0a3672e63058da6d98da95aa3cf2.jpg)
[high speed bus] Introduction to jesd204b

Ansible installation and use

Lay the foundation for children's programming to become a basic discipline

Simple and practical accounting software, so that accounts can be checked
随机推荐
Mysql表insert中文变?号的问题解决办法
DC-1靶场搭建及渗透实战详细过程(DC靶场系列)
C case of communication between server and client based on mqttnet
Summary of MySQL key challenges (2)
Learn what definitelytyped is through the typescript development environment of SAP ui5
Cultivate primary and secondary school students' love for educational robots
数学知识(欧拉函数)
Realize the function of data uploading
LeetCode-对链表进行插入排序
C # picture display occupancy problem
Mysql重点难题(2)汇总
Virtual machine installation deepin system
数学问题(数论)试除法做质数的判断、分解质因数,筛质数
Alibaba cloud polkit pkexec local rights lifting vulnerability
数据库问题汇总
Use of typescript classes
Embedded-c language-8-character pointer array / large program implementation
Learn BeanShell before you dare to say you know JMeter
2022-003arts: recursive routine of binary tree
Pytest learning ----- pytest Interface Association framework encapsulation of interface automation testing