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] 代码: ...
随机推荐
- Windows7下使用sphinx生成开源文档(原)
作者这里以osgearth文档为例,感觉这种生成文档的方式比较好,生成的html文档是支持搜索的,感谢开源工作者的奉献.赞一个 1. 下载并安装python for windows:https://w ...
- MVC5应用程序生命周期lifecycle
- python核心编程第3章课后题答案(第二版55页)
3-4Statements Ues ; 3-5Statements Use\(unless part of a comma-separated sequence in which case \ is ...
- UVa 1625 Color Length (DP)
题意:给定两个序列,让你组成一个新的序列,让两个相同字符的位置最大差之和最小.组成方式只能从一个序列前部拿出一个字符放到新序列中. 析:这个题状态表示和转移很容易想到,主要是在处理上面,dp[i][j ...
- Network in Network(NiN)
- Mlpconv layer with "micronetwork" with each conv layer to compute more abstract features ...
- Linux下为Eclipse安装hadoop插件
前提条件:在Linux系统中已经安装好了jdk和hadoop 本文的安装环境:1.arch Linux 2. hadoop1.0.1本地伪分布模式安装 3. Eclipse 4.5 1. 下载Ecl ...
- MariaDB 数据库迁移
一.为什么要迁移 我的七月小说站点放在JCloud上,恕我直言,配合我的Aliyun服务器进行数据交互,那是相当的慢,没办法,京东云上面十几块钱的公网ip,也就这样了. 所以我决定把web服务器和数据 ...
- GetPixelAddress()函数Alpha通道会丢失
CImage类中GetPixelAddress()函数来设置获取对应的颜色值是发现Alpha无效. void CGBImage::Load(){ CImage sourceImage; sourceI ...
- linux学习之路(4)
用户身份与文件权限 通过uid来区分: 管理员 UID 为 0:系统的管理员用户. 系统用户 UID 为 1-999: Linux 系统为了避免因某个服务程序出现漏洞而被黑客提 权至整台服务器,默认 ...
- C#中实现UrlEncode和UrlDecode
有时需要进行url编码.解码,比如从html中捞数据,有可能>.&等字符会被编码成>等. WinForm中默认没有引入System.Web,因此要现在项目中引入依赖 System. ...