1 leetcode-Two Sum
2016-11-07 20:02
309 查看
版本1
#!/usr/bin/python # -*- coding: utf-8 -*- ''' 英文: 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. 中文: 给一个整数数组,返回数组中相加等于target的两个数的索引. 假定每个输入都有符合要求的两个数 举例: Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1]. ''' class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ if len(nums) < 2: return "array error" Dict = {} #val->[index] for index,val in enumerate(nums): if Dict.has_key(val): Dict[val].append(index)#重复元素 else: Dict[val] = [index] for val in nums: if Dict.has_key(target - val): if (target - val) == val: if len(Dict[val]) < 2:#只有一个值为val的元素,重复使用,不能返回,第一次写的时候没考虑到,中枪了... continue else: return Dict[val][0:2] else: return [Dict[val][0],Dict[target - val][0]] if __name__ == "__main__": s = Solution() print s.twoSum([0,3,4,0],0) raw_input()
时间复杂度,空间复杂度都为O(n).
版本2,短小精悍…
class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ if len(nums) < 2: return "array error" for index,val in enumerate(nums): if (target - val) in nums[index + 1:]: return [index,index + 1 + nums[index + 1:].index(target - val)]
相关文章推荐
- [LeetCode] Two Sum
- leetcode No.1 Two Sum
- *LeetCode-Two Sum
- LeetCode(62)-Two Sum
- leetcode 1: 找出两个数相加等于给定数 two sum
- leetcode 刷题题解(c++) 1.Two Sum (hash表,排序+二分查找)
- LeetCode 学习笔记:Question 1、Two Sum
- leetcode-1 Two Sum 找到数组中两数字和为指定和
- LeetCode 1.Two Sum
- jiler的LeetCode学习笔记 java版本Two Sum
- Leetcode 1 Two Sum
- Leetcode 之第一题 two sum
- [LeetCode] Two Sum
- [Leetcode]1Two Sum
- LeetCode - Two Sum
- LeetCode:1. Two Sum
- leetcode 1 Two Sum
- [leetcode 1] Two Sum
- Leetcode学习(1)—— Two Sum
- 【Leetcode】Two Sum