【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. javascript: parse JSON

    $.get("/intra/do/sequence_has_codonList.pl",function(data){ data = JSON.parse(data); // ar ...

  2. thread.join 从异步执行变成同步

    Java的线程模型为我们提供了更好的解决方案,这就是join方法.在前面已经讨论过,join的功能就是使用线程 从异步执行变成同步执行 当线程变成同步执行后,就和从普通的方法中得到返回数据没有什么区别 ...

  3. 让C#轻松实现读写锁分离

    ReaderWriterLockSlim 类 表示用于管理资源访问的锁定状态,可实现多线程读取或进行独占式写入访问. 使用 ReaderWriterLockSlim 来保护由多个线程读取但每次只采用一 ...

  4. 剑指offer——树的子结构 (JAVA代码)

    版权声明:本文为博主原创文章,未经博主允许不得转载. 题目描述: 输入两棵二叉树A,B,判断B是不是A的子结构.(ps:我们约定空树不是任意一个树的子结构). 解题思路: 首先看牛客网给出的测试用例: ...

  5. EF简单的添加修改删除基本语法

    using ( androidhiveEntities db = new androidhiveEntities() )                {                    #re ...

  6. python:点赞功能

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/ ...

  7. IOS textField(textview)字数判断

    textfield 有时会需要设置字数限制,如果只是英文或者符号,可以直接在以下代理方法中判断字数 -(BOOL)textField:(UITextField *)textField shouldCh ...

  8. Nginx与Lua利用fpm打成rpm包

    1.下载相关软件 需要软件有:Nginx,LuaJIT,ngx_devel_kit,ngx_lua等安装文件 安装Lua或者LuaJIT都是可以的,但是出于效率的考虑,推荐安装LuaJITshell& ...

  9. [Spark] Spark的RDD编程

    本篇博客中的操作都在 ./bin/pyspark 中执行. RDD,即弹性分布式数据集(Resilient Distributed Dataset),是Spark对数据的核心抽象.RDD是分布式元素的 ...

  10. js 练习

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="req_form.aspx.cs ...