当前位置:网站首页>从数组中找出和为目标的下标
从数组中找出和为目标的下标
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}
}
边栏推荐
- Thinkphp内核工单系统源码商业开源版 多用户+多客服+短信+邮件通知
- LeetCode-归并排序链表
- Win10 disk management compressed volume cannot be started
- CubeMx DMA笔记
- Markdown edit syntax
- Vmware安装win10报错:operating system not found
- Rhcsa --- work on the fourth day
- How to configure PostgreSQL 12.9 to allow remote connections
- 洛谷入门3【循环结构】题单题解
- 06 装饰(Decorator)模式
猜你喜欢
数学知识——快速幂的理解及例题
How to modify data file path in DM database
Alibaba cloud polkit pkexec local rights lifting vulnerability
Idea autoguide package and autodelete package Settings
将光盘中的cda保存到电脑中
[understand one article] FD_ Use of set
06 装饰(Decorator)模式
Thinkphp内核工单系统源码商业开源版 多用户+多客服+短信+邮件通知
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
June book news | 9 new books are listed, with a strong lineup and eyes closed!
随机推荐
Mouse events in JS
Mysql重点难题(2)汇总
國產全中文-自動化測試軟件Apifox
Oracle stored procedure and job task setting
Geotrust OV Multi - Domain Domain SSL Certificate rmb2100 per year contains several Domain names?
正大留4的主账户信息汇总
LeetCode-归并排序链表
How do I interview for a successful software testing position? If you want to get a high salary, you must see the offer
Online incremental migration of DM database
June book news | 9 new books are listed, with a strong lineup and eyes closed!
Use of Baidu map
Mathematical knowledge -- understanding and examples of fast power
Application d'un robot intelligent dans le domaine de l'agroécologie
Lay the foundation for children's programming to become a basic discipline
案例分享|智慧化的西部机场
[graduation season · advanced technology Er] young people have dreams, why are they afraid of hesitation
Solution of DM database unable to open graphical interface
Summary of MySQL key challenges (2)
Super detailed pycharm tutorial
Rhcsa --- work on the fourth day