在数组中找到 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. Linux如何安装PHPMyAdmin

    1,我们要以root帐号登入 . 2,PHP支持模块安装.在CentOS操作系统安装完毕后,其实PHP支持模块并没有安装上去,如果想使用PhpMyAdmin,首先需要安装PHP支持模块,我们需要两个P ...

  2. JS原生实现html转pdf / html转图片 (html2canvas.js + jspdf.js )

    <button onclick="HtmlToPdf()"> 转储pdf </button> <button onclick="HtmlTo ...

  3. oeasy 教您玩转linux 之 010209 装酷利器 hollywood

    我们来回顾一下 上一部分我们都讲了什么? 屏幕故障风格的软件包bb 可以设置音频 这次装一个酷 下个hollywood软件包 apt show hollywood apt search hollywo ...

  4. oeasy教您玩转vim - 76 - # 组合键映射map

    ​ 会话session 回忆组合键映射的细节 上次我们定义了一系列的复合键 主要是和ctrl键一起 快速跳转window窗口 map <c-j> <c-w>j map < ...

  5. AT_arc113_c 题解

    洛谷链接&Atcoder 链接 本篇题解为此题较简单做法及较少码量,并且码风优良,请放心阅读. 题目简述 现在有一个字符串 \(S\),每一次你可以选择一个 \(i(1 \le i \le | ...

  6. 题解:AT_xmascon21_b Bad Mood

    AT_xmascon21_b Bad Mood 题意 给定你一个 \(n\times m\) 的矩形. 以一条对角线为基础上,制作一个无向图,该图的顶点对应于格子的共有 \((m+1) \times ...

  7. JVM系列(一) -浅谈虚拟机的成长史

    一.摘要 众所周知,Java 经过多年的发展,已经从一门单纯的计算机编程语言,发展成了一套成熟的软件解决方案.从互联网到企业平台,Java 是目前使用最广泛的编程语言. 以下这段内容是来自 Java ...

  8. vue项目锚点定位+滚动定位

    功能: HTML: js: scrollEvent(e) { let scrollItems = document.querySelectorAll('.condition-container') f ...

  9. 支付宝退款和结果查询接口简单实现(.Net 7.0)

    〇.前言 支付宝对 .Net 的支持还是比较充分的,在每个接口文档中都有关于 C# 语言的示例,这样就大大降低了对接的难度,很容易上手. 官方接口文档地址:退款-alipay.trade.refund ...

  10. web3 产品介绍:Decentraland:开启你的虚拟现实区块链游戏之旅

    Decentraland(https://decentraland.org/)是一款基于区块链技术的虚拟现实游戏,它将去中心化的概念引入游戏世界,为玩家提供了一个创造.交互和探索的虚拟空间.在Dece ...