two number sum

 

  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))
    复制代码

     

posted @   ascertain  阅读(17)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
历史上的今天:
2021-12-03 Ansible file module
2021-12-03 Allow non-root process to bind to port below 1024
点击右上角即可分享
微信分享提示