Python Two Sum - Brute Force Approach

2020-03-26 04:24发布

I'm new to Python and have just started to try out LeetCode to build my chops. On this classic question my code misses a test case.

The problem is as follows:

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, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].

I miss on test case [3,2,4] with the target number of 6, which should return the indices of [1,2], but hit on test case [1,5,7] with the target number of 6 (which of course returns indices [0,1]), so it appears that something is wrong in my while loop, but I'm not quite sure what.

class Solution:
    def twoSum(self, nums, target):
        x = 0
        y = len(nums) - 1
        while x < y:
            if nums[x] + nums[y] == target:
                return (x, y)
            if nums[x] + nums[y] < target:
                x += 1
            else:
                y -= 1
        self.x = x
        self.y = y
        self.array = array       
        return None

test_case = Solution()    
array = [1, 5, 7]
print(test_case.twoSum(array, 6))

Output returns null on test case [3,2,4] with target 6, so indices 1 and 2 aren't even being summarized, could I be assigning y wrong?

4条回答
小情绪 Triste *
2楼-- · 2020-03-26 04:51

Bit different approach. We will build a dictionary of values as we need them, which is keyed by the values we are looking for.If we look for a value we track the index of that value when it first appears. As soon as you find the values that satisfy the problem you are done. The time on this is also O(N)

class Solution:
    def twoSum(self, nums, target):
        look_for = {}
        for n,x in enumerate(nums):
            try:
                return look_for[x], n
            except KeyError:
                look_for.setdefault(target - x,n)

test_case = Solution()
array = [1, 5, 7]
array2 = [3,2,4]
given_nums=[2,7,11,15]
print(test_case.twoSum(array, 6))
print(test_case.twoSum(array2, 6))
print(test_case.twoSum(given_nums,9))

output:

(0, 1)
(1, 2)
(0, 1)
查看更多
Melony?
3楼-- · 2020-03-26 04:52
import itertools

class Solution:
    def twoSum(self, nums, target):
        subsets = []
        for L in range(0, len(nums)+1):
            for subset in itertools.combinations(nums, L):
                if len(subset)!=0:
                    subsets.append(subset)
        print(subsets) #returns all the posible combinations as tuples, note not permutations!
        #sums all the tuples
        sums = [sum(tup) for tup in subsets]
        indexes = []
        #Checks sum of all the posible combinations
        if target in sums:
            i = sums.index(target)
            matching_combination = subsets[i] #gets the option
            for number in matching_combination:
                indexes.append(nums.index(number))
            return indexes
        else:
            return None


test_case = Solution()    
array = [1,2,3]
print(test_case.twoSum(array, 4))

I was trying your example for my own learning. I am happy with what I found. I used the itertools to make all the combination of the numbers for me. Then I used list manipulation to sum all the possible combination of numbers in your input array, then I just check in one shot if the target is inside the sum array or not. If not then return None, return the indexes otherwise. Please note that this approach will return all the three indexes as well, if they add up to the target. Sorry it took so long :)

查看更多
forever°为你锁心
4楼-- · 2020-03-26 04:54

A brute force solution is to double nest a loop over the list where the inner loop only looks at index greater than what the outer loop is currently on.

class Solution:
    def twoSum(self, nums, target):
        for i, a in enumerate(nums, start=0):
            for j, b in enumerate(nums[i+1:], start=0):
                if a+b==target:
                    return [i, j+i+1]

test_case = Solution()
array = [3, 2, 4]
print(test_case.twoSum(array, 6))

array = [1, 5, 7]
print(test_case.twoSum(array, 6))

array = [2, 7, 11, 15]
print(test_case.twoSum(array, 9))

Output:

[1, 2]
[0, 1]
[0, 1]
查看更多
Juvenile、少年°
5楼-- · 2020-03-26 04:59
class Solution:
    def twoSum(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: List[int]
            """
            ls=[]
            l2=[]
            for i in nums:
                ls.append(target-i)

            for i in range(len(ls)):
                if ls[i] in nums  :
                    if i!= nums.index(ls[i]):
                        l2.append([i,nums.index(ls[i])])            
            return l2[0]


x= Solution()
x.twoSum([-1,-2,-3,-4,-5],-8)

output

[2, 4]
查看更多
登录 后发表回答