leetcode_No.1 Two Sum
原题:
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的更多相关文章
- LeetCode - Two Sum
Two Sum 題目連結 官網題目說明: 解法: 從給定的一組值內找出第一組兩數相加剛好等於給定的目標值,暴力解很簡單(只會這樣= =),兩個迴圈,只要找到相加的值就跳出. /// <summa ...
- 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 ...
- Leetcode 笔记 112 - Path Sum
题目链接:Path Sum | LeetCode OJ Given a binary tree and a sum, determine if the tree has a root-to-leaf ...
- POJ 2739. Sum of Consecutive Prime Numbers
Sum of Consecutive Prime Numbers Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 20050 ...
- BZOJ 3944 Sum
题目链接:Sum 嗯--不要在意--我发这篇博客只是为了保存一下杜教筛的板子的-- 你说你不会杜教筛?有一篇博客写的很好,看完应该就会了-- 这道题就是杜教筛板子题,也没什么好讲的-- 下面贴代码(不 ...
- [LeetCode] Path Sum III 二叉树的路径和之三
You are given a binary tree in which each node contains an integer value. Find the number of paths t ...
- [LeetCode] Partition Equal Subset Sum 相同子集和分割
Given a non-empty array containing only positive integers, find if the array can be partitioned into ...
- [LeetCode] Split Array Largest Sum 分割数组的最大值
Given an array which consists of non-negative integers and an integer m, you can split the array int ...
- [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 ...
随机推荐
- 大型分布式java应用与SOA
1.基于消息方式.远程调用方式的架构带来的问题: 1.1 系统多元化的问题 [解决]: 对共用逻辑部分进行抽象: 1.2 系统访问量.数据量上涨后带来的问题 [解决]: 拆分系统: 1.3 在构建共用 ...
- RTT学习之BSP
---恢复内容开始--- 一 根据相近型号的demo BSP进行修改制作自己的BSP https://github.com/RT-Thread/rt-thread/blob/master/bsp/st ...
- 牛客网Java刷题知识点之什么是进程、什么是线程、什么是多线程、多线程的好处和弊端、多线程的创建方式、JVM中的多线程解析、多线程运行图解
不多说,直接上干货! 什么是进程? 正在进行中的程序(直译). 什么是线程? 就是进程中一个负责程序执行的控制单元(执行路径). 见 牛客网Java刷题知识点之进程和线程的区别 什么是多线程? 一个进 ...
- idea编译golang插件总结
由于使用习惯了Idea 和vim插件.于是下载了idea的go插件并安装,可惜不支持go1.4 ,官方的go插件版本太低 133.326 — 133.9999 .只能手动编译 按照这个教程就可以 ht ...
- jQuery源代码学习_工具函数_type
jquery源代码学习_工具函数_type jquery里面有一个很重要的工具函数,$.type函数用来判断类型,今天写这篇文章,是来回顾type函数的设计思想,深入理解. 首先来看一下最终结果: 上 ...
- SQL内外连接的区别
项目当中,需要将SQL server中的部分数据导入mongo中,由于SQL是关系型数据库的原因,需要联合多表进行查询,因此,了解了下SQL中内外连接的相关概念,以作备注: 1.内联接(典型的联接运算 ...
- 了解委托(Delegate)
委托是一种全新面向对象语言特性,运行在.Net平台 基于委托,开发事件驱动程序变得非常简单 使用委托可以大大简化多线程变成的难度 理解委托 int a: //定义变量 a=100://给变量赋值 ...
- mac笔记本上的工具
svn可是换工具:cornerstone host修改工具:switchHosts!
- Vue.js双向数据绑定模板渲染
准备知识 1. 前端开发基础 html.css.js2. 前端模块化基础3. 对ES6有初步的了解 vuejs官网:cn.vuejs.org HTML: <!DOCTYPE html> & ...
- Android Studio快捷键【Android学习入门】
Studio快捷键[Android学习入门]" title="Android Studio快捷键[Android学习入门]"> 提示 Ctrl+P方法参数提示 Ct ...