LeetCode专题-Python实现之第1题:Two Sum
相关代码已经上传到github:https://github.com/exploitht/leetcode-python
文中代码为了不动官网提供的初始几行代码内容,有一些不规范的地方,比如函数名大小写问题等等;更合理的代码实现参考我的github repo
1、读题
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, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
有一个整型数组,返回满足特定条件的2个数字的索引,这2个数字相加的值等于特定的目标数字。假设每一次输入都会有唯一的输出而且同一个元素不会使用2次。
2、初步解题
很简单的一个思路就是循环遍历数组,做一个if判断,满足条件返回索引。编码很简单,如下:
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
# i从列表的第一个到倒数第二个,也就是nums[0, Len-2]
# j从i的后面一个开始到nums[Len-1]
# 下面的len(nums)-1而不是-2是因为range(1,2)返回的是[1]不含2
for i in range(0, len(nums) - 1):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
return [i, j]
3、第一次优化
上面的解决方案for套for明显时间复杂度是O(n2),这里的2是平方,空间复杂度是O(n),思考一下有没有优化的办法的?
循环有嵌套,能不能不要循环套循环?
这里的循环嵌套是为了对每一个元素判断一次序列中是否有匹配元素,有的话返回双方索引,所以可以考虑在寻找匹配的元素这一步,不要一直去遍历,如果元素值和索引生成一个哈希表,那么匹配的过程只要查询哈希表就行了,这个过程的复杂度是O(1),下面尝试给出一种解决方案:
class Solution(object):
def twoSum(self, nums, target):
num_dict = dict()
# 第一次循环建立值和索引的哈希表
for index, value in enumerate(nums):
num_dict[value] = index
# 第二次循环判断目标target-nums里的元素得到的结果是不是在前面得到的字典中,如果存在则返回双方索引
for index, value in enumerate(nums):
if (target - value) in num_dict and num_dict[target - value] != index:
return [index, num_dict[target - value]]
4、第二次优化
上面一个方案通过2次循环(非嵌套)的方式,遍历了2次nums列表得到了需要的结果,时间复杂度变成了O(n)。
美中不足的是循环还是进行了2次,这里是先生成一个哈希表,然后循环过程中判断当前元素和哈希表中的数据相加是否满足条件,第一次循环的过程中能不能做一个判断呢?
所以下一个思路是遍历nums,遍历过程中判断当前元素和哈希表中的值相加能不能满足要求,也就是target-当前元素的值在哈希表中是否存在,如果存在,就返回2个索引,如果不存在,那么当前元素存入哈希表。实现如下:
class Solution(object):
def twoSum(self, nums, target):
num_dict = dict()
for index, value in enumerate(nums):
want = target - value
if want in num_dict:
return [num_dict[want], index]
num_dict[value] = index
声明:文章中涉及的代码全部本地手写然后上传到leetcode验证通过,优化部分思路参考官网内容
LeetCode专题-Python实现之第1题:Two Sum的更多相关文章
- LeetCode专题-Python实现之第28题: Implement strStr()
导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...
- LeetCode专题-Python实现之第27题:Remove Element
导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...
- LeetCode专题-Python实现之第26题:Remove Duplicates from Sorted Array
导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...
- LeetCode专题-Python实现之第21题:Merge Two Sorted Lists
导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...
- LeetCode专题-Python实现之第20题:Valid Parentheses
导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...
- LeetCode专题-Python实现之第9题:Palindrome Number
导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...
- LeetCode专题-Python实现之第14题:Longest Common Prefix
导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...
- LeetCode专题-Python实现之第13题:Roman to Integer
导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...
- LeetCode专题-Python实现之第7题:Reverse Integer
导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...
随机推荐
- 支持不同Android设备,包括:不同尺寸屏幕、不同屏幕密度、不同系统设置
Some of the important variations that you should consider include different languages, screen sizes, ...
- 我的 FPGA 学习历程(11)—— 实验:按键消抖
按键是一个输入设备,在理论上可以归为开关一类,理想的按键波形如下: 然而由于按键的机械特性,断开和闭合动作是不可能在一瞬间完成的,实际的波形如下: 抖动期间电平处于临界值,由于晶振的频率相当的高,数字 ...
- BZOJ3592 : Architext
首先特判多边形面积$=0$的情况,此时内部没有点,答案只会在顶点处取到. 对于面积$>0$的情况,离线询问,将所有多边形合在一起得到平面图,然后求出对偶图,那么每条多边形边的两侧分别对应对偶图中 ...
- 安装selenium
步骤: 1.下载setuptools2.点击安装setuptools.exe3.安装成功后,python的安装目录下会有Scripts的文件夹4.配置环境变量:python安装目录\Scripts5. ...
- C++ otlv4 连接 sql server 数据库小记
otlv4介绍: http://otl.sourceforge.net/ 测试代码 // testotlv4.cpp : 定义控制台应用程序的入口点. // #include "stdafx ...
- nodejs编译遇到的问题
src\node_contextify.cc:631: Assertion 'args[1]->IsString()' failed. node 10 版本会出现这个问题, 安装natives后 ...
- Deepin下配置JDK8
下载JDK 首先在http://www.oracle.com/technetwork/java/javase/downloads/index.html下载对应的JDK 本人下载的是JDK8 解压tar ...
- mybatis的配置和使用
mybatis的配置和使用 MyBatis 是支持定制化 SQL.存储过程以及高级映射的优秀的持久层框架.MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集.MyBatis ...
- 一个开源的,跨平台的.NET机器学习框架ML.NET
微软在Build 2018大会上推出的一款面向.NET开发人员的开源,跨平台机器学习框架ML.NET. ML.NET将允许.NET开发人员开发他们自己的模型,并将自定义ML集成到他们的应用程序中,而无 ...
- [Swift]LeetCode106. 从中序与后序遍历序列构造二叉树 | Construct Binary Tree from Inorder and Postorder Traversal
Given inorder and postorder traversal of a tree, construct the binary tree. Note:You may assume that ...