【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 日期 题目地 ...
随机推荐
- SQLite的优化总结
网上关于SQL优化的教程很多,但是比较杂乱.近日有空整理了一下,写出来跟大家分享一下. 1.对查询进行优化,要尽量避免全表扫描,首先应考虑在 where 及 order by 涉及的列上建立索引. 2 ...
- linux 下的信号量参数
linux 下的信号量参数 转载自:http://blog.itpub.net/26110315/viewspace-718306/ 信号量是一种锁机制用于协调进程之间互斥的访问临界资源.以确保某种共 ...
- HttpEntity转换Inputstream(红色)加XmlPull解析
package com.bawei.xml; import java.io.IOException; import java.io.InputStream; import java.util.Arra ...
- ecshop二次开发之常用函数及汇总
lib_time.php gmtime()说明:获得当前格林威治时间的时间戳 server_timezone()说明:获得服务器的时区 local_mktime($hour = NULL , $min ...
- JS判断输入是否为整数的正则表达式
1.正确表达式 "^\\d+$" //非负整数(正整数 + 0)"^[0-9]*[1-9][0-9]*$" //正整数"^((-\\d+)|(0+ ...
- windows页面打印div(弹出新页面)
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http ...
- 24-React Components组件
Components 组件 1.组件 可以让UI独立的分割出来,可以让UI重复利用. 2.组件就像是JavaScript函数,它们能够接收任意的输入(称为"props",即属性)并 ...
- 18-ES6(1)
第18课-ES6(1) 模块化 1.export和import // model.js export default let m = 1; // 出错 export default n = 2; le ...
- Excel的数据导入到PB的DW中
Excel的数据导入到PB的DW中//==================================================================== // Event:cb_ ...
- Python虚拟开发环境
最近,一直在不同版本的Python之间来回折腾,发现了几个Python虚拟开发环境工具,具体如下: 1. Virtualenv,可以指定开发环境的Python版本.继承已有开发环境配置,virtual ...