Python, developed locally works, but doesn't work on LeetCode


  • 0
    M

    I'm trying to do a LeetCode question:

    Given an array of integers, find two numbers such that they add up to
    a specific target number.

    The function twoSum 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 (both index1 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

    The first try was using two for loops, which gave me O(n^2), and unfortunately it didn't pass. Hence I tried to use:

    target - current = index
    

    And search for if the index does exists on a dictionary.

    This is my code:

    class Solution:
        def twoSum(self, nums, target):
            dic = {}
            
            #A number can appear twice inside the same index, so I use a list
            for i in xrange(0, len(nums)):
                try:
                    dic[nums[i]].append(i)
                except:
                    dic[nums[i]] = []
                    dic[nums[i]].append(i)
              
            try:
                for items_1 in dic[nums[i]]:
                    for items_2 in dic[target-nums[i]]:
                        if(items_1+1 != items_2+1):
                            l = []
                            if(items_2+1 > items_1+1):
                                l.append(items_1+1)
                                l.append(items_2+1)
                            else:
                                l.append(items_2+1)
                                l.append(items_1+1)
                            return l
            except:
                pass
    

    I developed this locally, and I was able get the correct result with one of the test case that LeetCode was complaining: [-3,4,3,90], 0

    The output I got was [1, 3], but on LeetCode it returned null, does anybody know why this would happen?


Log in to reply
 

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