leetcode-Two sum(最佳思路以及python代码实现)
2018-03-22 10:17
579 查看
1、Two sum
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].答案:使用hashtable,建立数组值和下标的键值对,在python中相当于使用dict来存储,dict的key是数组的值,数组的下标是dict的value。
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
dict = {} # 定义一个字典
for i in xrange(len(nums)): # 遍历数组
x = nums[i] # 取当前数组的值
if target-x in dict: # 如果target减去当前值的差在字典的key中可以找到,直接可以返回dtarget-x对应的值,也即下标
return (dict[target-x], i) # 返回当前下标和找到的下标
dict[x] = i # 将数组值和下标数存入dict
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].答案:使用hashtable,建立数组值和下标的键值对,在python中相当于使用dict来存储,dict的key是数组的值,数组的下标是dict的value。
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
dict = {} # 定义一个字典
for i in xrange(len(nums)): # 遍历数组
x = nums[i] # 取当前数组的值
if target-x in dict: # 如果target减去当前值的差在字典的key中可以找到,直接可以返回dtarget-x对应的值,也即下标
return (dict[target-x], i) # 返回当前下标和找到的下标
dict[x] = i # 将数组值和下标数存入dict
相关文章推荐
- leetcode 617. Merge Two Binary Trees Python实现以及and操作符用法
- leetcode two sum python 实现
- 【LeetCode】【Python】【C++】2. Add Two Numbers代码实现
- [leetcode]Two Sum C++ python实现
- LeetCode 64 Minimum Path Sum(Python详解及代码实现)
- [LeetCode]1 Two Sum(C++,Python实现)
- 排序算法总结以及python代码实现
- leetcode 【 Merge Two Sorted Lists 】 python 实现
- LeetCode Two Sum 题库记录--代码小白开始码代码的人生,第一天!
- Leetcode平台上的TwoSum题目用Java哈希表实现
- [leetcode]Two Sum @ Python
- leetcode two sum python
- 1. Two Sum Leetcode Python New season for 2016
- LeetCode(1) Two Sum实现
- 【LeetCode-面试算法经典-Java实现】【001-Two Sum(求两个数的和)】
- Redis订阅&发布以及python代码实现
- leetcode 【 Add Two Numbers 】 python 实现
- Leetcode_two-sum (c++ and python version)
- [LeetCode]题解(python):001-Two-Sum
- [LeetCode]2 Median of Two Sorted Arrays (C++,Python实现)