LeetCode: 1. Two Sum python
来源:互联网 发布:特斯拉潜能软件下载 编辑:程序博客网 时间:2024/05/18 00:17
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.
Example:
Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].看题目的意思,只要找出两个数相加等于target就行了。
再看提示有哈希,那就用哈希吧,在python中,哈希就是个字典。试了一下,我用nums的值当key,target-nums[i]的值当value,下面贴代码
- class Solution(object):
- def twoSum(self, nums, target):
- """
- :type nums: List[int]
- :type target: int
- :rtype: List[int]
- """
- mDict = {}
- for i in range(len(nums)):
- if mDict.has_key(nums[i]):
- return [nums.index(mDict[nums[i]]),i]
- else:
- mDict[target - nums[i]] = nums[i]
- del mDict
- 其实很简单,大家可以看着代码体会一下,文字不是很好表达。
0 0
- 1.Two Sum Leetcode Python
- [Leetcode] 1.Two Sum @python
- LeetCode: 1. Two Sum python
- Leetcode: 1. Two Sum [python]
- [leetcode:python]1.Two Sum
- leetcode 1. Two Sum python
- 【Leetcode】【python】Two Sum, Two Sum II
- LEETCODE 1.Two Sum (python实现)
- Leetcode题解(Python): 1.Two Sum
- 【Leetcode】【Python】【C++】1. Two Sum实现
- LeetCode 1.Two Sum (Python)
- 【leetcode】1. Two Sum(Python & C++)
- LeetCode 1. Two Sum Python Solution
- leetcode two sum python 实现
- 【LeetCode with Python】 Two Sum
- LeetCode : No1 Two Sum Python
- [leetcode]-[Two Sum]-python实现
- [Leetcode.python] 001. Two Sum
- Lint学习使用
- 多线程_03_线程池
- JVM--java内存模型
- Java编程思想学习笔记(一) 第2章 一切都是对象
- 高通平台MSM8916LCM模块移植(一)-bootloader部分
- LeetCode: 1. Two Sum python
- MySQL数据库优化总结如果索引多个字段,第一个字段要是经常作为查询条件的。如果只有第二个字段作为查询条件,这个索引不会起到作用;
- todo 数据结构算法
- Opencv学习三-图像的载入,显示和输出
- HDU1096
- JQuery学习笔记(一)
- 把整型数据转为最低2进制最高36进制的字符串
- windows平台下caffe可视化配置
- Redis 入门