Python twoSum problem


  • 0
    Y
        class Solution:
        # @return a tuple, (index1, index2)
    	def twoSum(self, num, target):
    		dict_num = {}
    		(index1, index2) = (0, 0)
    		for i in range(len(num)):
    			try:
    				flag = dict_num[target - num[i]]
    			except KeyError:
    				dict_num[num[i]] = i
    			else:
    				index1 = flag + 1
    				index2 = i + 1
    				break
    		return (index1, index2)
    
    numbers = [2, 7, 11, 15]
    target = 9
    a = Solution()
    index = a.twoSum(numbers, target)
    print "%d, %d" % (index[0], index[1])
    

    I have tried this code in sublime successfully, but it didn't work well in leetcode...Could you tell me where is wrong?


  • 0
    Y

    class Solution:

    @return a tuple, (index1, index2)

    def twoSum(self, num, target):
    dict_num = {}
    (index1, index2) = (0, 0)
    for i in range(len(num)):
    try:
    flag = dict_num[target - num[i]]
    except KeyError:
    dict_num[num[i]] = i
    else:
    index1 = flag + 1
    index2 = i + 1
    break
    return (index1, index2)

    This is the answer.... TT


  • 0
    F

    As you are using dict to maintain the map from num to its index, it will fail when where are several duplicate items.
    For example, [0, 3, 3, 4] for target 7, I think the answer should be (2,4), but for your code, it will be (3,4).
    So, that's it.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.