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 ...
随机推荐
- uva 133解题报告
题目描述 为了缩短领救济品的队伍,NNGLRP决定了以下策略:每天所有来申请救济品的人会被放在一个大圆圈,面朝里面.选定一个人为编号 1 号,其他的就从那个人开始逆时针开始编号直到 N.一个官员一开始 ...
- Vuejs 实现权限管理
程序运行时,router只配置登陆 首页404 等基本页面 import Main from '@/views/Main.vue'; // 不作为Main组件的子页面展示的页面单独写,如下 expor ...
- nginx —— 理解nginx_upstream_jvm_route模块解决tomcat多节点session不一致问题
这种方式不需要修改web工程只需要对nginx下载nginx_upstream_jvm_route插件,修改tomcat和nginx配置,就能解决session问题.由于这种方式不会把session存 ...
- Dev Express Report 学习总结(二)关于如何使用Grouping分组
对于所有的报表工具来说,基本上所有Grouping功能的都很相似.正如前面说到的,Group处于Page Header和Page Footer之间,同时又将Detail包括与其中. 下面还是通过一个例 ...
- cookie 跨域访问
废话不知道该说些什么...先看代码吧. cookie 是浏览器保存在用户计算机上的少量数据 //读取cookie function getCookie(name) { var arr, reg = n ...
- pl/sql 如何配置连接远程一个或多个数据库
参考链接 https://blog.csdn.net/yy_love_my/article/details/45720277
- Oracle基础篇--01数据库控制语言DCL
数据库控制语言,是用户对数据的权限控制语言. 通过GRANT语句进行赋权,通过REVOKE撤回权限.数据库的权限包括2种,一种是数据库系统权限,一种是数据库对象权限.在控制语言里面,存在2个概念, 1 ...
- [转]IE和FireFox中JS兼容之event .
转载于:http://blog.csdn.net/jiachunfeng/article/details/6448186 http://justcoding.iteye.com/blog/587876 ...
- .NET控制台程序监听程序退出
There are mainly 2 types of Win32 applications, console application and window application. They hav ...
- 动态配置log4j2.xml日志输出文件的位置
目标:根据启动jar时传进main()的参数动态修改日志位置 一.修改启动项 MainMapLookup.setMainArguments(args);注:不要在lookup设置之前初始化log(如: ...