【LeetCode】#1 Two Sum
【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:
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
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:
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)\).
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:
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)\),但比此前的方案少了一半的常数项。
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的更多相关文章
- 【LeetCode】813. Largest Sum of Averages 解题报告(Python)
[LeetCode]813. Largest Sum of Averages 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博 ...
- 【LeetCode】113. Path Sum II 解题报告(Python)
[LeetCode]113. Path Sum II 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fu ...
- 【LeetCode】167. Two Sum II - Input array is sorted
Difficulty:easy More:[目录]LeetCode Java实现 Description Given an array of integers that is already sor ...
- 【LeetCode】170. Two Sum III – Data structure design
Difficulty:easy More:[目录]LeetCode Java实现 Description Design and implement a TwoSum class. It should ...
- 【LeetCode】1005. Maximize Sum Of Array After K Negations 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 小根堆 日期 题目地址:https://leetco ...
- 【LeetCode】938. Range Sum of BST 解题报告(Python & C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归 日期 题目地址:https://leetcod ...
- 【LeetCode】167. Two Sum II - Input array is sorted 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 Java解法 Python解法 日期 题目地址:ht ...
- 【LeetCode】1. Two Sum 两数之和
作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 个人公众号:负雪明烛 本文关键词:two sum, 两数之和,题解,leetcode, 力 ...
- 【LeetCode】437. Path Sum III 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 DFS + DFS BFS + DFS 日期 题目地 ...
随机推荐
- dev TreeList拖拽
一.说明 使用dev控件,TreeList1向TreeList2拖拽 二.属性 //允许拖拽 treeList1.AllowDrop = true; tre ...
- JavaScript---function、this关键字相关习题
1. 请看下列代码: function F( ){ function C( ){ return this; } return C(); } var o=new F( ); 请问上面的this值指向的是 ...
- solr 4.6的安装配置
从网上看了很多资料,很多都是老的.自己也算是结合着弄出来了. 1.下载的准备工作 tomcat8.solr4.6 具体的下载自己去找去吧.或者后期我在提供. 2.开始配置 tomcat路径:E:\ ...
- noi 6047 分蛋糕
题目链接:http://noi.openjudge.cn/ch0405/6047/ 和Uva1629很类似,不过,可能用记忆化难写一点,状态初始化懒得搞了.就用循环好了. 状态描叙也可以修改,那个题目 ...
- [LeetCode_5] Longest Palindromic Substring
LeetCode: 5. Longest Palindromic Substring class Solution { public: //动态规划算法 string longestPalindrom ...
- wkhtmltopdf 安装使用笔记(CentOS6)
1. 在官网下载安装文件. http://wkhtmltopdf.org/ 安装时如果提示某些库找不到的话,使用yum安装即可. 2. 命令行测试 $ wkhtmltopdf http://news. ...
- Duiib 创建不规则窗口(转载)
方法一: 转载:http://blog.csdn.net/chenlycly/article/details/46447297 转载:http://blog.csdn.net/harvic880925 ...
- docker设置并运行部分命令及原文
1.设置开机启动 If you want Docker to start at boot, you should also: $ sudo systemctl enable docker 2. 启动, ...
- jquery ajax异步请求
得先知道后台接口给ajax访问(接口URl和传入接口的参数及参数类型),知道访问之后返回的数据类型,有哪些数据. 选择异步请求的方式,常用的有三种,如$.ajax().$.post().$.get ...
- Hibernate 继承映射
@Entity@Inheritance(strategy=InheritanceType.SINGLE_TABLE)@DiscriminatorColumn()public class Animal ...