Python Two Sum - Brute Force Approach

后端 未结 5 706
谎友^
谎友^ 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

    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]
    

提交回复
热议问题