Two Sum [easy] (Python)
由于题目说了有且只有唯一解,可以考虑两遍扫描求解:第一遍扫描原数组,将所有的数重新存放到一个dict中,该dict以原数组中的值为键,原数组中的下标为值;第二遍扫描原数组,对于每个数nums[i]查看target-nums[i]是否在dict中,若在则可得到结果。
当然,上面两遍扫描是不必要的,一遍即可,详见代码。
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
keys = {}
for i in xrange(len(nums)):
if target - nums[i] in keys:
return [keys[target - nums[i]], i]
if nums[i] not in keys:
keys[nums[i]] = i
Two Sum [easy] (Python)的更多相关文章
- LeetCode--Array--Two sum (Easy)
1.Two sum (Easy)# Given an array of integers, return indices of the two numbers such that they add u ...
- 【leetcode】Minimum Path Sum(easy)
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which ...
- 【leetcode】Two Sum (easy)
Given an array of integers, find two numbers such that they add up to a specific target number. The ...
- [leetcode]Path Sum II @ Python
原题地址:https://oj.leetcode.com/problems/path-sum-ii/ 题意: Given a binary tree and a sum, find all root- ...
- leetcode:Path Sum【Python版】
1.类中递归调用函数需要加self # Definition for a binary tree node # class TreeNode: # def __init__(self, x): # s ...
- leetcode 【 Minimum Path Sum 】python 实现
题目: Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right w ...
- [leetcode] #112 Path Sum (easy)
原题链接 题意: 给定一个值,求出从树顶到某个叶(没有子节点)有没有一条路径等于该值. 思路: DFS Runtime: 4 ms, faster than 100.00% of C++ class ...
- leetcode Combination Sum II python
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in ...
- Leetcode——Two Sum(easy)
题目:Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1] 代码: ...
随机推荐
- 命令之 ulimit
help ulimit help ulimit ulimit: ulimit [-SHacdefilmnpqrstuvx] [limit] Modify shell resource limits. ...
- Java WEB中的HttpServletResponse数据传递
1.什么是HttpServletResponse 2.使用HttpServletResponse向浏览器发送数据及相关实例. 实例1:实现文件下载功能 实例2:实现验证码注册 实例3:实现页面3秒后跳 ...
- 编写高质量代码改善C#程序的157个建议——建议18:foreach不能代替for
建议18:foreach不能代替for 上一个建议中提到了foreach的两个优点:语法更简单,默认调用Dispose方法,所有我们强烈建议在实际的代码编写中更多的使用foreach.但是,该建议也有 ...
- How Tomcat Works(十九)
本文重点关注启动tomcat时会用到的两个类,分别为Catalina类和Bootstrap类,它们都位于org.apachae.catalina.startup包下:Catalina类用于启动或关闭S ...
- PostBack
PostBack 字面意义 Post提交 Back回来. 提交回来. 1. AutoPostBack 服务器控件需要设置 AutoPostBack="true" 后才会提交服务器. ...
- go的同步模型
首先来看一段代码,这是The Go Memory Model一文中的一个例子 var a, b int func f() { a = 1 b = 2 } func g() { ...
- 关于小程序bindregionchange事件在IOS崩溃的问题
先说下原因,我在bindregionchange事件触发函数中设置了经纬度,而latitude和longitude是绑定在map组件上的,滑动地图的过程中重新设置了地图中心点的经纬度,会导致地图本身的 ...
- 主流C语言编译器介绍
- opencv.js小案例
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> ...
- 【bzoj3512】DZY Loves Math IV 杜教筛+记忆化搜索+欧拉函数
Description 给定n,m,求\(\sum_{i=1}^{n}\sum_{j=1}^{m}\varphi(ij)\)模10^9+7的值. Input 仅一行,两个整数n,m. Output 仅 ...