simple dumb python, very ez to understand


  • 0
    B
    class Solution(object):
        def twoSum(self,nums, target):
            result = []
            for idx, num in enumerate(nums):
                nums[idx] = ''
                if (target-num) in nums:
                    result.append(idx)
                nums[idx] = num
            return result

  • 0
    B

    Consider this input. num=[1,2,3,4,5,6], target=8

    Your solution would return more than 2 indices. 4 to be exact [1,2,3,5]. Also, It is not guaranteed that the matching indices are next to each other either, as this output shows.

    Here is my solution:

    class Solution(object):
        def twoSum(self, nums, target):
            d = {}
            for i, num in enumerate(nums):
                if target-num in d:
                    return [d[target-num], i]
                else:
                    d[num] = i
            return None
    

    A dictionary works really here because of the constant time look ups. I used the num as the key and the indices as the value. Once all nums are in the dictionary, The loop will iterator checking for the needed to reach the target, and if it is found it will return the pair of indices.


  • 0
    B

    @betts your answer is very standard way using hashmap. I come up with this solutions because it says in the questions
    "You may assume that each input would have exactly one solution."


  • 0
    B

    this is very true


  • 0
    S

    @betts The question states that there is "Exactly one solution", so wouldn't your example of [1,2,3,4,5,6] be incorrect.


  • 0
    B

    @sam yes it would.


  • 0
    H

    @betts you can try it : nums=[0,4,3,0] target=0. your answer is [3,3].


  • 0
    B

    @hqhz1817 you are correct, I have revised the solution.

    class Solution(object):
        def twoSum(self, nums, target):
            d = {}
            for i, num in enumerate(nums):
                if target-num in d:
                    return [d[target-num], i]
                else:
                    d[num] = i
            return None
    

Log in to reply
 

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