【Question】

  • Given an array of integers, return indices of the two numbers such that they add up to a specific target.

    You may assume that each input would have exactly one solution.

  • Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,

return [0, 1].


【My Solution】

  • Brute Force
class Solution(object):
def twoSum_update(self, nums ,target):
"""
Brute Force: Loop through each element x
find if there is another value that equals to target - x
"""
l = len(nums)
for i in range(l):
for j in range(i+1, l):
if (nums[i] == target - nums[j]):
return [i,j]
raise ValueError("No two sum solution")
  • 分析

    双重循环遍历查询满足条件的数值

  • Complexity Analyze:

  1. Time complexity : \(O(n^2)\). For each element, we try to find its complement by looping through the rest of array which takes \(O(n)\) time. Therefore, the time complexity is \(O(n^2)\). 容易出现TLE

  2. Space complexity : \(O(1)\).


【Other Solution #1】

  • Two-pass Hash Table 两段式哈希表
class Solution(object):
def twoSum(self, nums ,target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
l = len(nums)
hash = {}
for i in range(l):
hash[nums[i]] = i
for i in range(l):
if target-nums[i] in hash and hash[target-nums[i]]!=i:
return [i, hash[target-nums[i]]]
raise ValueError("No two sum solution")
  • 分析

    利用Python中的dict来进行对求差所得的数值的查找。由于dict采用哈希结构,查找所需时间接近 \(O(1)\) (在发生冲突时可能会退化到 \(O(n)\) ),通过空间换取时间。最简单的实现方式是采用两轮循环,第一轮将每个元素及其索引添加进哈希表,第二轮检查当前元素对于target的补数是否在这个表中,另外要注意的是该补数不能是当前元素。

  • Complexity Analyze:

  1. Time complexity : \(O(n)\). We traverse the list containing n elements exactly twice. Since the hash table reduces the look up time to \(O(1)\), the time complexity is \(O(n)\).

  2. Space complexity : \(O(n)\). The extra space required depends on the number of items stored in the hash table, which stores exactly n elements.


【Other Solution #2】

  • One-pass Hash Table 一段式哈希表
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
l = len(nums)
hash_map = {}
for i in range(l):
if target-nums[i] in hash_map:
return [hash_map[target-nums[i]], i]
hash_map[nums[i]] = i
raise ValueError("No two sum solution")
  • 分析

    基于上面的两段式哈希表,可以改进成一段式哈希表,在循环遍历元素的时候进行哈希表的插入,并且可以同时回头查询当前元素的补数是否也存在于表中,存在的话可以立即返回。

  • Complexity Analysis:

  1. Time complexity : \(O(n)\). We traverse the list containing nn elements only once. Each look up in the table costs only \(O(1)\) time. 虽然同样是 \(O(n)\),但比此前的方案少了一半的常数项。

  2. Space complexity : \(O(n)\). The extra space required depends on the number of items stored in the hash table, which stores at most n elements. 空间上也比此前方案有了一定的优化,有时并不需要完全遍历一遍元素。

【LeetCode】#1 Two Sum的更多相关文章

  1. 【LeetCode】813. Largest Sum of Averages 解题报告(Python)

    [LeetCode]813. Largest Sum of Averages 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博 ...

  2. 【LeetCode】113. Path Sum II 解题报告(Python)

    [LeetCode]113. Path Sum II 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fu ...

  3. 【LeetCode】167. Two Sum II - Input array is sorted

    Difficulty:easy  More:[目录]LeetCode Java实现 Description Given an array of integers that is already sor ...

  4. 【LeetCode】170. Two Sum III – Data structure design

    Difficulty:easy  More:[目录]LeetCode Java实现 Description Design and implement a TwoSum class. It should ...

  5. 【LeetCode】1005. Maximize Sum Of Array After K Negations 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 小根堆 日期 题目地址:https://leetco ...

  6. 【LeetCode】938. Range Sum of BST 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归 日期 题目地址:https://leetcod ...

  7. 【LeetCode】167. Two Sum II - Input array is sorted 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 Java解法 Python解法 日期 题目地址:ht ...

  8. 【LeetCode】1. Two Sum 两数之和

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 个人公众号:负雪明烛 本文关键词:two sum, 两数之和,题解,leetcode, 力 ...

  9. 【LeetCode】437. Path Sum III 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 DFS + DFS BFS + DFS 日期 题目地 ...

随机推荐

  1. QT 中文显示问题

    在QT4 中,要显示中文,都是要这样写: #include <QTextCodec> QTextCodec::setCodecForTr(QTextCodec::codecForLocal ...

  2. php常用array函数

    http://www.w3school.com.cn/php/php_ref_array.asp 1.array_change_key_case() 把数组中所有键更改为小写或大写2.array_ch ...

  3. Salesforce 执行顺序

    在服务器上,Salesforce按以下顺序执行: 1,从数据库加载原始记录或初始化一个用于更新插入(upsert)语句的记录. 2,从请求加载新记录的字段值并覆盖旧的值. 如果请求来自一个标准的UI( ...

  4. CI 框架导出文件

    CI框架目录结构: |-application (应用目录) |-system (核心目录) |-downexcel (文件存在目录) |-ZipBackDir (备份目录) |-index.php ...

  5. 2 . Linux常见命令

    Linux常见命令格式: 命令名称 选项 参数 ls -alh 文件/目录 --all #ls 显示当前目录内容 #ls -l 显示文件详细信息 #ls -hl h已常见单位显示文件大小 k M G# ...

  6. python操作文件案例二则

    前言 python 对于文件及文件夹的操作. 涉及到 遍历文件夹下所有文件 ,文件的读写和操作 等等. 代码一 作用:查找文件夹下(包括子文件夹)下所有文件的名字,找出 名字中含有中文或者空格的文件 ...

  7. Uva 1629 切蛋糕

    题目链接:https://vjudge.net/contest/146179#problem/B 题意:一个矩形蛋糕上有好多个樱桃,现在要做的就是切割最少的距离,切出矩形形状的小蛋糕,让每个蛋糕上都有 ...

  8. jquery学习方法

    http://www.runoob.com/jquery/jquery-tutorial.html jQuery 语法 通过 jQuery,您可以选取(查询,query) HTML 元素,并对它们执行 ...

  9. Fragment碎片

    布局文件中添加碎片 1.在onCteate()方法中调用inflater.inflate()加载Fragment布局 2.在xml的<fragment>中需要显示指明碎片名称(androi ...

  10. 关于APP程序员泡沫经济

    这些年,移动互联网非常火,火到掀起学习iOS.安卓以及H5的热潮.有人将这些新技术作为自己的实力补充,增加竞争力:更多的人将它们作为主业,专职做移动开发.但是,即便有移动开发人员不断涌入,对整个行业来 ...