原题:  

  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.

翻译:

  给出一个数字列表和一个目标值(target),假设列表中有且仅有两个数相加等于目标值,我们要做的就是找到这两个数,并返回他们的索引值。

举例:

Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

解答: 

# 方法1:双层循环,面试不会通过,时间复杂度太高
def twoSum_way1(self,nums,target):
"""
:param nums: 整数列表
:param target:目标值
:return:result 索引值
"""
result = []
for i in range(len(nums)):
for j in range(i+1,len(nums)):
if nums[i] + nums[j] == target:
result.append(i)
result.append(j)
return result #方法2:通过判断target与某一个元素的差值是否也在列表之中,类似方法1,同样是面试官不期望的回答
def twoSum_way2(self,nums,target):
"""
:param nums: 整数列表
:param target:目标值
:return:result 索引值
"""
result = []
for i in range(len(nums)):
first_num = nums[i]
second_num = target - first_num
if second_num in nums:
j = nums.index(second_num)
if i != j:
result.append(i)
result.append(j)
return result

  

#适合面试的方法:
#方法3:通过创建字典,将nums里的值和序号对应起来,
# 并创建另一个字典存储目标值(Target)-nums的值,
# 通过判断该值是否在nums内进行判断并返回其对应索引值
class Solution:
def twoSum_way3(self, nums, target):
"""
:param nums: 整数列表
:param target:目标值
:return:result 索引值
"""
#创建第一个字典:用于存储整数列表nums的元素值和对应索引
num_dict = {nums[i]: i for i in range(len(nums))}
#创建第二个字典:存储target-列表中的元素的值
num_dict2 = {i: target - nums[i] for i in range(len(nums))}
#判断num_dict2的值是否是输入列表中的元素,如果是返回索引值,不是则往下进行
result = []
for i in range(len(nums)):
j = num_dict.get(num_dict2.get(i))
if (j is not None) and (j != i):
result = [i,j]
break
return result #方法4:改进方法3,让代码简洁一些
class Solution:
def twoSum_way4(self, nums, target):
"""
:param nums: 整数列表
:param target:目标值
:return:result 索引值
"""
num_dict = {nums[i]: i for i in range(len(nums))}
for i in range(len(nums) -1):
difference = target - nums[i]
if difference in num_dict and i != num_dict[difference]:
return [i,num_dict[difference]]
return None

终极写法:

class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
dict = {}
for index,num in enumerate(nums):
another_num = target - num
dict[num] = index
if another_num in dict:
return [dict[another_num], index]
return None

  

  

  

 

leetcode_No.1 Two Sum的更多相关文章

  1. LeetCode - Two Sum

    Two Sum 題目連結 官網題目說明: 解法: 從給定的一組值內找出第一組兩數相加剛好等於給定的目標值,暴力解很簡單(只會這樣= =),兩個迴圈,只要找到相加的值就跳出. /// <summa ...

  2. Leetcode 笔记 113 - Path Sum II

    题目链接:Path Sum II | LeetCode OJ Given a binary tree and a sum, find all root-to-leaf paths where each ...

  3. Leetcode 笔记 112 - Path Sum

    题目链接:Path Sum | LeetCode OJ Given a binary tree and a sum, determine if the tree has a root-to-leaf ...

  4. POJ 2739. Sum of Consecutive Prime Numbers

    Sum of Consecutive Prime Numbers Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 20050 ...

  5. BZOJ 3944 Sum

    题目链接:Sum 嗯--不要在意--我发这篇博客只是为了保存一下杜教筛的板子的-- 你说你不会杜教筛?有一篇博客写的很好,看完应该就会了-- 这道题就是杜教筛板子题,也没什么好讲的-- 下面贴代码(不 ...

  6. [LeetCode] Path Sum III 二叉树的路径和之三

    You are given a binary tree in which each node contains an integer value. Find the number of paths t ...

  7. [LeetCode] Partition Equal Subset Sum 相同子集和分割

    Given a non-empty array containing only positive integers, find if the array can be partitioned into ...

  8. [LeetCode] Split Array Largest Sum 分割数组的最大值

    Given an array which consists of non-negative integers and an integer m, you can split the array int ...

  9. [LeetCode] Sum of Left Leaves 左子叶之和

    Find the sum of all left leaves in a given binary tree. Example: 3 / \ 9 20 / \ 15 7 There are two l ...

随机推荐

  1. Django-1 简介

    1.1 MVC与MTV模型 MVCWeb服务器开发领域里著名的MVC模式,所谓MVC就是把Web应用分为模型(M),控制器(C)和视图(V)三层,他们之间以一种插件式的.松耦合的方式连接在一起,模型负 ...

  2. HBuilder的常用快捷键

    Ctrl + d 删除整行内容 Ctrl + Shift +R 复制当前行到下一行 Ctrl + Shift +D 重新编辑 Ctrl + 方向键 当前行整行内容上移或下移 Alt + ↓ 跳转到下一 ...

  3. CTeX里面CTRL-Space和中文输入法的冲突问题解决

    我使用的是windows xp,相信下面的方法也能应用到win7等windows系统上. 我希望在CTex套件的WinEdt 6.0里使用模板自动插入内容时,想快速从上到下遍历” * “并修改. 通过 ...

  4. Dropping Balls UVA - 679(二叉树的遍历)

    题目链接:https://vjudge.net/problem/UVA-679 题目大意:t组样例,每组包括D M   层数是D   问第M个小球落在哪个叶子节点?    每个节点有开关  刚开始全都 ...

  5. 快速排序算法的实现 && 随机生成区间里的数 && O(n)找第k小 && O(nlogk)找前k大

    思路:固定一个数,把这个数放到合法的位置,然后左边的数都是比它小,右边的数都是比它大 固定权值选的是第一个数,或者一个随机数 因为固定的是左端点,所以一开始需要在右端点开始,找一个小于权值的数,从左端 ...

  6. auto uninstaller 简体中文版 更新下载地址

    地址一(腾讯微云) 地址二(百度网盘)    提取码:3nx7 地址三(直接下载)

  7. hduoj 2062Subset sequence

    Subset sequence Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)T ...

  8. pat1091. Acute Stroke (30)

    1091. Acute Stroke (30) 时间限制 400 ms 内存限制 65536 kB 代码长度限制 16000 B 判题程序 Standard 作者 CHEN, Yue One impo ...

  9. 修改mysql表的字符集

    ALTER TABLE logtest CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci; 修改数据库字符集: 代码如下: ALTER DAT ...

  10. 通过一个例子,总结下检测数组属性的N种方法

    判断arr数组里是否含有a,有a返回1;没有返回2var arr = [{a:1,b:2,c:3},{q:1,w:2,e:3},{s:4,g:5,i:9},{b:2,v:3,u:4}]; 检测属性的3 ...