原题:  

  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. thinkPHP 全局函数

    M函数 TP的Model父类,封装的功能比较多,增删改查操作都具备.一些表,比如留言表,comment class CommentModel extends Model { } M('comment' ...

  2. Vue.js-----轻量高效的MVVM框架(一、初识Vue.js)

    1.什么是Vue.js? 众所周知,最近几年前端发展非常的迅猛,除各种框架如:backbone.angular.reactjs外,还有模块化开发思想的实现库:sea.js .require.js .w ...

  3. 数据库版本管理工具flyway

    引入flyway_core  jar包 java 代码实现 public class FlywayMigration { @Resource private DataSource dataSource ...

  4. Android中的时间格式的校验

    public class MainActivity extends Activity implements OnClickListener{ private Button btn1; private ...

  5. LeanTouch控制移动

    Lean_Touch控制移动 using UnityEngine; using System.Collections; using System.Collections.Generic; using ...

  6. Andrew Ng 的 Machine Learning 课程学习 (week2) Linear Regression

    这学期一直在跟进 Coursera上的 Machina Learning 公开课, 老师Andrew Ng是coursera的创始人之一,Machine Learning方面的大牛.这门课程对想要了解 ...

  7. Apache-ant安装以及环境变量配置、验证

    (一)安装 ant 下载地址: http://ant.apache.org/     根据自己电脑下载对应版本 下载完成以后,可自行解压到自己常用的盘中,但是要记住解压到哪里了,以便后续的环境变量配置 ...

  8. [Eclipse]自动注释功能

    1) 新建一个file时,加上一些注释的方法. window->preference->java->code     styple->code     template 当你选 ...

  9. pyhon虚拟环境的安装和使用

    安装Python2.7: 1.Mac下使用Python2.7 2.Windows下安装Python2.7. *从python官网下载python2.7的版本 *双击python2.7,然后选择安装路径 ...

  10. js超链接

    _blank -- 在新窗口中打开链接 _parent -- 在父窗体中打开链接 _self -- 在当前窗体打开链接,此为默认值 _top -- 在当前窗体打开链接,并替换当前的整个窗体(框架页) ...