导航页-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. 平时作业七 Java

    以下是几本计算机书籍的基本信息编号 书名 价格 出版社1 JAVA基础 32 清华大学出版社2 JAVA WEB开发 40 电子工业出版社3 面向对象程序设计 28 清华大学出版社4 Struts开发 ...

  2. 953.Verifying an Alien Dictionary(Map)

    In an alien language, surprisingly they also use english lowercase letters, but possibly in a differ ...

  3. 1.Git安装

    1.安装 首先下载安装包https://git-scm.com/downloads/ 双击安装任意盘符,双击之后一路Next,当然也可以修改默认配置 安装结束!

  4. springboot整合mybatis和mybatis-plus

    问题 1 分页查询问题 2   mybatis的配置由mybatis变成mybatis-plus 3  Mybatis-plus中的Wrapper

  5. win7下配置mysql的my.ini文件

    一.环境 操作系统是win7 x64, mysql是5.6.40. 二. 怎么配置? 修改my.ini文件, 添加[client], 在下面加一行 default-character-set=utf8 ...

  6. 简单工厂模式demo

    1. 简单工厂模式 domain的接口 public interface Color{ public void display(); } red public Class Red implements ...

  7. python Ajax

    Ajax一.准备知识JSON1.什么是json JSON 指的是 JavaScript 对象表示法(JavaScript Object Notation) JSON 是轻量级的文本数据交换格式 JSO ...

  8. Linux atop监控

    200 ? "200px" : this.width)!important;} --> 介绍 atop是一个功能非常强大的linux服务器监控工具,它的数据采集主要包括:CP ...

  9. javascript 省市区三级联动 附: json数据

    html: <label> <span>购买地址</span> <select name="PurchaseProvince" style ...

  10. 微信小程序 + mock.js 实现后台模拟及调试

    一.创建小程序项目 mock.js 从 https://github.com/nuysoft/Mock/blob/refactoring/dist/mock.js 下载 api.js:配置模拟数据和后 ...