导航页-LeetCode专题-Python实现

相关代码已经上传到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的更多相关文章

  1. LeetCode专题-Python实现之第28题: Implement strStr()

    导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...

  2. LeetCode专题-Python实现之第27题:Remove Element

    导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...

  3. LeetCode专题-Python实现之第26题:Remove Duplicates from Sorted Array

    导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...

  4. LeetCode专题-Python实现之第21题:Merge Two Sorted Lists

    导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...

  5. LeetCode专题-Python实现之第20题:Valid Parentheses

    导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...

  6. LeetCode专题-Python实现之第9题:Palindrome Number

    导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...

  7. LeetCode专题-Python实现之第14题:Longest Common Prefix

    导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...

  8. LeetCode专题-Python实现之第13题:Roman to Integer

    导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...

  9. LeetCode专题-Python实现之第7题:Reverse Integer

    导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...

随机推荐

  1. python学习:列表

    列表 a = ['abc','bcd','cde','def','efg']print(a)列表的操作:增删改查 1)查:切片print(a[1:3]) #从'bcd'取到'cde',列表取值顾头不顾 ...

  2. List使用linq的OrderBy方法排序,并按照两个字段排序的写法

    SfaMember.GetList(searchInfo, 0, 1000, out Allcount).Where(item => item.bOpen == true).OrderBy(it ...

  3. iview修改tabbar实现小程序自定义中间圆形导航栏及多页面登录功能

    emmm,用iview改了个自定义中间圆形的tabbar. 如下图所示, 重点,什么鬼是“多页面登录”? 例如:我现在要做一个功能,要说自己长得帅才能进去页面. 一个两个页面还好,但是我现在要每个页面 ...

  4. 《SpringMVC从入门到放肆》十三、SpringMVC数据校验

    上一章,我们学习了SpringMVC的自定义类型转换器,但是如果转换后的数据传递到Controller的方法中,忽然发现有某些属性为Null了,这怎么办?我们需要一种有效的数据校验机制,来对数据进行有 ...

  5. 详解node + mongoDb(mongoDb安装、运行,在node中连接、增删改查)

    一.序言 好久没写博客了,这次主要聊聊 node 和 mongoDb . 先说明一下技术栈  node + express + mongoose + mongoDb.这篇博客,主要讲述 mongoDb ...

  6. linux 使用sh@d0ws0cks server

    [root@linux-node1 ~]# cat /etc/shadowsocks.json { "server":"x.x.x.x", , "lo ...

  7. Oracle 查询表空间使用情况

    select *   from (Select a.tablespace_name,                to_char(a.bytes / 1024 / 1024, '99,999.999 ...

  8. MySQL 分区建索引

    200 ? "200px" : this.width)!important;} --> 介绍 mysql分区后每个分区成了独立的文件,虽然从逻辑上还是一张表其实已经分成了多张 ...

  9. CAS实现单点登录SSO执行原理及部署

    一.不落俗套的开始 1.背景介绍 单点登录:Single Sign On,简称SSO,SSO使得在多个应用系统中,用户只需要登录一次就可以访问所有相互信任的应用系统. CAS框架:CAS(Centra ...

  10. Angularjs中的缓存以及缓存清理

    写在最前面:这篇博文是2篇文章组成,详细介绍了Angularjs中的缓存以及缓存清理,文章由上海尚学堂转载过来,欢迎大家阅读和评论.转载请注明出处,谢谢! 一个缓存就是一个组件,它可以透明地储存数据, ...