python解决两个数之和等于给定目标值问题

需求:给定一些数,找出两个数之和等于目标值N

方法一:利用双指针方法解决

def twoSum1(nums, target):
    res = []
    newnums = nums[:]  # 深拷贝原数组到新数组
    newnums.sort()  # 排序
    left = 0  # 左指针
    right = len(nums) - 1  # 右指针
    while left < right:
        if newnums[left] + newnums[right] == target:
            for i in range(0, len(nums)):
                if nums[i] == newnums[left]:
                    res.append(i)
                elif nums[i] == newnums[right]:
                    res.append(i)
            res.sort()
            break
        elif newnums[left] + newnums[right] < target:
            left = left + 1
        elif newnums[left] + newnums[right] > target:
            right = right - 1

    return (res[0] + 1, res[1] + 1)

if __name__ == '__main__':
    nums = [3, 7, 10, 4, 5]
    target = 11
    print(twoSum1(nums, target))

方法二:利用哈希算法解决

def towSum2(nums, target):
    dict = {}
    for i in range(len(nums)):
        m = nums[i]  # 当前待查询的数字
        if target - m in dict:  # 判断target - m是否存在字典中
            return (dict[target - m] + 1, i + 1)
        dict[m] = i


if __name__ == '__main__':
    nums = [3, 7, 10, 4, 5]
    target = 11
    print(towSum2(nums, target))

注意:哈希算法解决查找问题,不仅效率高、代码少而且容易理解,查询问题能用哈希解决的,尽量用哈希算法

你可能感兴趣的:(算法,求两数之和,python,哈希算法)