原题:  

  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. my.答题

    20170821增加: http://www.119you.com/mhxy/yxgl/738653.shtml 1.三界奇缘 http://my.netease.com/forum.php?mod= ...

  2. Jmeter录制pc脚本

    1.打开jmeter后可以看到左边窗口有个“测试计划”和“工作台”,右键“测试计划”,添加 Threads(Users) →线程组,再右键 线程组→添加 配置元件→Http请求默认值 Http请求默认 ...

  3. js arguments 和 reduce求和

    1.js arguments arguments 是一个对应于传递给函数的参数的类数组对象 function sum(){ ; ; i < arguments.length; i++){ sum ...

  4. cmake中文帮助文档

    CMake的 在这个页面 了解CMake的生成命令 在摇篮使用cmake变量 报告问题 使用过Android Studio 2.2及更高版本,可以使用NDK和CMake的 编译C和C ++代码到本机库 ...

  5. 2019.03.21 读书笔记 ==与Equals

    首先得出一个结论:==是比较变量内存的数据,Equals是值比较.但是他们都能被重写,所以object又增加了一个RefrenceEquals不可被重写,只比较数据: [ReliabilityCont ...

  6. PlayMaker Play Sound 和 Audio Play

    这两个 Action 都可以播放声音 *Play Sound:只要把声音拖进去就可以: *Audio Play:要求游戏对象要有Audio Source组件.

  7. Qmake 配置自定义编译过程

    Qmake 配置自定义编译过程 需求:动态更换资源文件 在 Windows10 下编写 Qt 项目时,有这样的需求: 程序用到的资源文件可以动态更换而不需要重新编译整个项目 解决方案 0.1 将所有的 ...

  8. IIS报错试图加载格式不正确的程序集解决办法 64位WinServer系统兼容32位程序集

    问题描述:     将网站/WCF发布到IIS后运行报这个错. 原因:     64位系统和32系统不匹配导致. 解决办法:     方法一.注册32位IIS(必须卸载64位IIS)         ...

  9. 如何快速定位JVM中消耗CPU最多的线程?

    第一步.先找出Java的进程PID ps -ef | grep 进程名关键字 这里假设找到的PID是:12345   第二步.找出该进程内最消耗CPU的线程 top -Hp log4x R :11.7 ...

  10. mysql-查询(DQL)

    + 注释:mysql中的+号只有一个作用,就是运算符,没有连接字符串的作用,连接字符串用concat. ;两个操作数都是数值型,则做加法运算. ; :只要其中有一个时字符型,则会试图将字符转换为数值型 ...