Python Two Sum - Brute Force Approach

后端 未结 5 704
谎友^
谎友^ 2021-01-14 06:04

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:

5条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-14 07:05

    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]
    

提交回复
热议问题