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 文中代码为了不动官网提供的初始 ...
随机推荐
- kaggle之泰坦尼克号乘客死亡预测
目录 前言 相关性分析 数据 数据特点 相关性分析 数据预处理 预测模型 Logistic回归训练模型 模型优化 前言 一般接触kaggle的入门题,已知部分乘客的年龄性别船舱等信息,预测其存活情况, ...
- linux的软件安装方式总结
Linux系统中软件的“四”种安装原理详解:源码包安装.RPM二进制安装.YUM在线安装.脚本安装包 一.Linux软件包分类 1.1 源码包 优点: 开源,如果有足够的能力,可以修改源代码: 可 ...
- centos7系统下搭建docker本地镜像仓库
## 准备工作 用到的工具, Xshell5, Xftp5, docker.io/registry:latest镜像 关于docker的安装和设置加速, 请参考这篇博文centos7系统下 docke ...
- css 制作导航条布局
代码: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8 ...
- [LeetCode] Prime Palindrome 质数回文数
Find the smallest prime palindrome greater than or equal to N. Recall that a number is prime if it's ...
- 771. Jewels and Stones
You're given strings J representing the types of stones that are jewels, and S representing the ston ...
- PHP环境在7以上的项目报错A non-numeric value encountered
报错如下图: 解决办法: 在相对应的报错控制器层加入一行代码,需加载控制器上方,代码如下: ini_set("error_reporting","E_ALL & ...
- 2019PHP面试题最全面归纳总结
1.请选择以下代码运行的结果: <?php if ('1e3' == '1000') echo 'LOL'; ?> A 无任何输出结果 B LOL C 不执行且报错 解析:1e3 ...
- python+SQLAlchemy+爬虫
python+SQLAlchemy+爬虫 前面分享了SQLAlchemy的知识,这次我共享一下学习用python开发爬虫再把爬出来的数据放到用SQLAlchemy的数据库上面的知识,当然我这个是带测试 ...
- seed实验——Set-UID Program Vulnerability实验
一.实验描述 Set-UID是Unix OS中的一个·非常重要的安全机制.当一个Set-UID程序运行的时候,它具有代码拥有者的权限.举个例子,如果代码的拥有者是root用户,那么不论任何用户运行该程 ...