【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. DOM的基本属性

    结构和内容属性1.1 nodeType1.2 nodeName, tagName1.3 innerHTML1.4 innerHTML pitFalls1.5 nodeValue 总结DOM节点是一个对 ...

  2. FTPClient使用中的问题--获取当前工作目录为null

    使用org.apache.commons.net.ftp.FTPClient 来做ftp的上传下载功能 FTPClient ftp = new FTPClient();ftp.connect(doc. ...

  3. SCALA XML pattern attrbute(属性)

    from: Working with Scala's XML Support 虽然这个guy炒鸡罗嗦,但是还是讲到我要的那句话:  Because Scala doesn't support XML ...

  4. [转]struct.pack 用法手记

    原文:http://hi.baidu.com/tibelf/item/8b463d15edfdf10bd1d66d83 看到在进行c格式的二进制文件读取的过程中,用到了struct.unpack方法, ...

  5. linux系统一键安装phpstudy的lnmp环境

    phpStudy for Linux 支持Apache/Nginx/Tengine/Lighttpd, 支持php5.2/5.3/5.4/5.5切换 已经在centos-6.5,debian-7.4. ...

  6. [转]Java中Map的用法详解

    转载地址:http://www.zhixing123.cn/jsp/30113.html Map简介 将键映射到值的对象.一个映射不能包含重复的键:每个键最多只能映射到一个值.此接口取代 Dictio ...

  7. springMVC下集成active MQ发送邮件

    环境:本地需安装activemq,且访问正常,安装方法网上很多,这里省略. 1.添加相关jar包,我这里使用的是maven,你也可以选择其他方式添加.下面是maven相关配置: <!-- Act ...

  8. ANGULAR JS WATCH监听使用(详)

    ANGULAR 监听使用: 当angular数据模型发生变化时,我们需要如果需要根据他的变化触发其他的事件. $watch是一个scope函数,用于监听模型变化,当你的模型部分发生变化时它会通知你. ...

  9. iOS开发,URL编码和解码

    URL传递数据中,如果含有中文,需要进行编码: NSString *urlEncodeString = [urlStr stringByAddingPercentEncodingWithAllowed ...

  10. Intellij jrebel 热部署

    Intellij 14破解下载 注册机 即可进行破解.JRebel安装下载IntelliJ IDEA的 JRebel插件: jr-ide-idea-6.2.0-idea-13-14.zip. 打开In ...