twoSum Algorithm : How to improve this?

前端 未结 22 2345
礼貌的吻别
礼貌的吻别 2021-02-06 01:38

I felt like doing an algorithm and found this problem on leetcode

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

22条回答
  •  自闭症患者
    2021-02-06 01:51

    I tried most of the answers and they don't seem to handle the edge cases properly. Hence, throwing my two cents for python3 solution that handles the edge cases. I used Max's algorithm to implement it:

       def twoSum(nums, target):
        output=[]
        arr=sorted(nums)
        x=0
        y=-1
        X=len(nums)-1
        while x  target):
                X-=1 
            elif (arr[X]+arr[x] <  target):
                x+=1
            elif (arr[X]+arr[x] == target):
                #print("Found",arr[X],arr[x])
                num1=arr[x]
                num2=arr[X]
                x+=1
                X-=1 
        for i in range(len(nums)):
            if num1 == nums[i] and y==-1:
                index1=i
                y=i
            elif num2 == nums[i]:
                index2=i         
        return [index1, index2]
    

    N.B. It's important to consider edge cases and inputs like the following

    print(twoSum([3,2,4],  6)) # [1,2]
    print(twoSum([3,3],  6))  # [0,1]
    

提交回复
热议问题