在数组中找到 2 个数之和等于给定值的数字,结果返回 2 个数字在数组中的下标。

1. 解法1 时间复杂度 O(n^2)

直接两次遍历所有节点,进行求和比较

代码如下:

func twoSum(nums []int, target int) []int {
res := make([]int, 2, 2)
for i:= 0;i<len(nums);i++{
for j:=i+1;j<len(nums);j++{
if nums[i]+nums[j]==target{
res[0] =i
res[1]=j
}
}
}
return res
}

2.解法2: 时间复杂度O(n)

只需要遍历一次所有元素,用 哈希表(键值对表)进行存储即可: 只要数字总和,那么每遍历一次数组,就可以算出他的求和的另一个数字的值,在接下来的遍历中如果找到了就成功得到答案,否则返回Nil

字典就是哈希表的实现。

代码如下:

func twoSum(nums []int, target int) []int {
data := make(map[int]int)
for i := 0; i < len(nums); i++ {
another := target - nums[i]
if _, ok := data[another]; ok {
return []int{data[another], i}
}
data[nums[i]]=i
}
return nil
}

语法熟悉

Go多重赋值

if _, ok := m[another]; ok {

首先执行;前的内容,在Go中,根据键访问map会返回两个值,第一个值是这个键对应的值,第二个值是该键是否存在,如果存在返回True,否则False。接下根据OK是否为真判断是否进入后续语句。

return []int{data[another], i }

如果存在,就说明当前位置的元素的另一半存在于这个哈希表中,就访问成功了,那么找到满足要求的两个数,需要返回他俩的下标,这个哈希表中键是元素,值是下标,就返回即可。

如果没有找到另一半,就将这个元素加入到哈希表中,由于是在哈希表中查找,那么哈希表中的元素必然在原Array中位置靠前,所以应先返回哈希表中的元素。

1. Two Sum Go实现的更多相关文章

  1. LeetCode - Two Sum

    Two Sum 題目連結 官網題目說明: 解法: 從給定的一組值內找出第一組兩數相加剛好等於給定的目標值,暴力解很簡單(只會這樣= =),兩個迴圈,只要找到相加的值就跳出. /// <summa ...

  2. Leetcode 笔记 113 - Path Sum II

    题目链接:Path Sum II | LeetCode OJ Given a binary tree and a sum, find all root-to-leaf paths where each ...

  3. Leetcode 笔记 112 - Path Sum

    题目链接:Path Sum | LeetCode OJ Given a binary tree and a sum, determine if the tree has a root-to-leaf ...

  4. POJ 2739. Sum of Consecutive Prime Numbers

    Sum of Consecutive Prime Numbers Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 20050 ...

  5. BZOJ 3944 Sum

    题目链接:Sum 嗯--不要在意--我发这篇博客只是为了保存一下杜教筛的板子的-- 你说你不会杜教筛?有一篇博客写的很好,看完应该就会了-- 这道题就是杜教筛板子题,也没什么好讲的-- 下面贴代码(不 ...

  6. [LeetCode] Path Sum III 二叉树的路径和之三

    You are given a binary tree in which each node contains an integer value. Find the number of paths t ...

  7. [LeetCode] Partition Equal Subset Sum 相同子集和分割

    Given a non-empty array containing only positive integers, find if the array can be partitioned into ...

  8. [LeetCode] Split Array Largest Sum 分割数组的最大值

    Given an array which consists of non-negative integers and an integer m, you can split the array int ...

  9. [LeetCode] Sum of Left Leaves 左子叶之和

    Find the sum of all left leaves in a given binary tree. Example: 3 / \ 9 20 / \ 15 7 There are two l ...

  10. [LeetCode] Combination Sum IV 组合之和之四

    Given an integer array with all positive numbers and no duplicates, find the number of possible comb ...

随机推荐

  1. Windows系统下DoH配置小记

    Windows系统下DoH配置小记 浏览器 Edge 打开edge://settings/privacy 使用安全的 DNS 指定如何查找网站的网络地址 设置自定义服务商为https://doh.op ...

  2. [oeasy]python0010_怎么用命令行保存文件

    编写 py 文件 回忆上次内容 上次 真的输出了 程序员的浪漫 Hello world!   print函数 可以输出 字符串 但是 print这个词 别拼错 就连 大小写 也别能错 错了就改 也没事 ...

  3. SMU Summer 2024 Contest Round 1(7.8)zhaosang

    A-A http://162.14.124.219/contest/1005/problem/A 一道数学问题,求概率. 要求成功的概率,有两个色子, 一个用来抛正反面,一个用来控制得分大小,当超过某 ...

  4. pandas无法打开.xlsx文件,xlrd.biffh.XLRDError: Excel xlsx file; not supported

    原因是最近xlrd更新到了2.0.1版本,只支持.xls文件.所以pandas.read_excel('xxx.xlsx')会报错. 可以安装旧版xlrd,在cmd中运行: pip uninstall ...

  5. iOS开发基础142-广告归因

    IDFA IDFA是苹果为iOS设备提供的一个唯一标识符,专门用于广告跟踪和相关的营销用途.与之对应的,在Android平台的是谷歌广告ID(Google Advertising ID). IDFA的 ...

  6. canvas实现截图功能

    开篇 最近在做一个图片截图的功能. 因为工作时间很紧张, 当时是使用的是一个截图插件. 周末两天无所事事,来写一个简单版本的截图功能. 因为写的比较简单,如果写的不好,求大佬轻一点喷 读取图片并获取图 ...

  7. 【Mybatis】12 复杂关联查询

    一对多 & 多对一 关联查询 数据库准备: 一个班级表,字段:班级ID + 班级名称 一个学生表,字段:学生ID + 学生姓名 + 所属的班级ID # 班级表 班级ID+班级名称 CREATE ...

  8. 【转载】英特尔CEO:如果美出口管制太严,中国就必须生产自己的芯片

    原文地址: https://mbd.baidu.com/newspage/data/landingsuper?context={"nid"%3A"news_9816136 ...

  9. 读《Simple statistical gradient-following algorithms for connectionist reinforcement learning》论文 提出Reinforce算法的论文

    <Simple statistical gradient-following algorithms for connectionist reinforcement learning>发表于 ...

  10. C# 遇见System.Net.Http不兼容的解决方案

    背景 假设我有一个项目A,调用B项目里面的HttpClient.A里面的System.Net.Http引用路径为(版本4.0.0.0) C:\Program Files (x86)\Reference ...