码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode Two Sum

时间:2015-02-02 14:10:58      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:

#title : Two Sum
#Given an array of integers, find two numbers such
#that they add up to a specific target number.
#The function two Sum should return indices of the
#two numbers such that they add up to the target,
#where index1 must be less than index2. Please note 
#that your returned answers (bothindex1 and index2)
#are not zero-based.
#You may assume that each input would have exactly 
#one solution.
#Input: numbers={2, 7, 11, 15}, target=9
#Output: index1=1, index2=2

# First method O(n^2)
#easy but Time Limit Exceeded
# class Solution:
# 	# @return a tuple,(index1, index2)
# 	def twoSum(self, num, target):
# 		for i in range(len(num)):
# 			for j in range(i+1,len(num)):
# 				if (num[i] + num[j] == target):
# 					return (i+1,j+1)

#Second method O(n) HashTable
#HashTable store the number‘s index
class Solution:
	# @return a tuple,(index1, index2)
	def twoSum(self, num, target):
		num_hashtable = dict()
		result_tuple = tuple()
		mul_hash = dict()
		for i in range(len(num)):
			#the key don‘t repeat 
			if num[i] in num_hashtable:
				mul_hash[num[i]] = i
			else:
			#the key do repeat
				num_hashtable[num[i]] = i
		print mul_hash
		print num_hashtable
		for i in range(len(num)):
			gap = target - num[i]
			#two cases
			#first : don‘t have same number
			if gap >= 0 and gap != num[i]:
				if num_hashtable.has_key(gap):
					result_tuple = (i+1,num_hashtable[gap]+1)
					return result_tuple
			#second : have same number
			elif gap >= 0 and gap == num[i]:
				if gap in mul_hash:
					result_tuple = (i+1,mul_hash[gap]+1)
					return result_tuple


if __name__ == ‘__main__‘:
	twoSum = Solution()
	num = [3,2,5,7,3]
#	num = [0,0,3,2,8,9,7,8,9,7]
#	num = 0
	target = 6
	print twoSum.twoSum(num, target)

  

Leetcode Two Sum

标签:

原文地址:http://www.cnblogs.com/xieweichong/p/4267549.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!