首页 > 其他分享 >two number sum

two number sum

时间:2022-12-03 21:47:57浏览次数:55  
标签:palindrome goal int sum two number high low array

 

  1. nested loop
    remand = [3, 5, -4, 8, 11, 1, -1, 6]
    goal = 10
    
    
    def palindrome(array: list[int], goal: int) -> tuple:
        length = len(array)
        for i in range(length - 1):
            for j in range(i + 1, length):
                if array[i] + array[j] == goal:
                    return array[i], array[j]
        return ()
    
    
    print(palindrome(remand, goal))

     

  2. dict
    remand = [3, 5, -4, 8, 11, 1, -1, 6]
    goal = 10
    
    
    def palindrome(array: list[int], goal: int):
        v = {}
        for b in array:
            mate = goal - b
            if mate in v:
                return mate, b
            v[b] = None
        return ()
    
    
    print(palindrome(remand, goal))

     

  3. cursor: low high
    remand = [3, 5, -4, 8, 11, 1, -1, 6]
    goal = 10
    
    
    def palindrome(array: list[int], goal: int) -> tuple:
        array.sort()
        low, high = 0, len(array) - 1
        while low < high:
            if array[low] + array[high] < goal:
                low += 1
            elif array[low] + array[high] > goal:
                high -= 1
            else:
                return array[low], array[high]
        return ()
    
    
    print(palindrome(remand, goal))

     

标签:palindrome,goal,int,sum,two,number,high,low,array
From: https://www.cnblogs.com/dissipate/p/16948818.html

相关文章