Leetcode-Algorithms Two Sum
2017-02-26 11:13
330 查看
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.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
给出一个integer数列和一个integer,return一个包含 在给出的数列中两个数之和是给出的integer的index的 数列。只有唯一解。
这是一个最简单的方法,但是runtime太高。
用哈希runtime会快很多因为只有一个loop。
当list的数不在dict的时候,target减这个数的值为key,value为此数。当list的数为在dict为key的时候查找就完成了。
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
给出一个integer数列和一个integer,return一个包含 在给出的数列中两个数之和是给出的integer的index的 数列。只有唯一解。
这是一个最简单的方法,但是runtime太高。
class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ for p1 in range(len(nums)): for p2 in range(p1+1,len(nums)): if((nums[p1]+nums[p2]) == target): return [p1,p2]
用哈希runtime会快很多因为只有一个loop。
class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ if len(nums) <= 1: return False buff_dict = {} for i in range(len(nums)): if nums[i] in buff_dict: return [buff_dict[nums[i]], i] else: buff_dict[target - nums[i]] = i
当list的数不在dict的时候,target减这个数的值为key,value为此数。当list的数为在dict为key的时候查找就完成了。
相关文章推荐
- [LeetCode-Algorithms-1] "Two Sum" (2017.9.8)
- 【Leetcode】Sum of Two Integers
- LeetCode------Two Sum
- leetcode — two-sum
- LeetCode|Sum of Two Integers
- LeetCode Two Sum
- LeetCode——two sum of integer
- LeetCode-algorithms 39. Combination Sum
- 【LeetCode】Two Sum II - Input array is sorted 解题报告
- 371.[LeetCode]Sum of Two
- LeetCode 1 Two sum Java
- Leetcode 1. Two Sum (Easy) (cpp)
- Leetcode 712. Minimum ASCII Delete Sum for Two Strings
- Two Sum leetcode java
- LeetCode 371 Sum of Two Intergers
- LeetCode 371 : Sum of Two Integers(Java)
- 《leetcode》two-sum
- Two Sum LeetCode OJ
- LeetCode – Refresh – Two Sum II
- Two Sum Leetcode Python Java