常见面试算法题:给定数组中寻找加和为特定数的两个数

本文介绍LeetCode经典题目“两数之和”的高效解法,通过排序及双指针技巧找到目标和的两个数,并注意返回其在原数组中的下标,避免重复使用同一元素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

leetcode上问题描述:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:
Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

解题的思路对是数组做排序,然后设置两个指针,分别从最大值和最小值两头开始,判断两个指针对应的数值相加与目标值的区别,来调整两个指针移动的位置。最终会选取到所需的那两个数。空间复杂度O(n),时间复杂度O(nlogn + n)。

在实现上述思路过程中,要注意题目的关键点:
1. 返回的是那两个数在原数组中的index,而非这两个数的具体值
2. 同一个元素不能使用两次

这两个关键点也正是题目的两个坑。针对关键点一:千万不要返回排序后的index,要用个dict记录原始数组中各值的index;针对关键点二:切记原数组中是允许多个数值相同的情况。一开始我使用dict记录计数时,key=原数组中的数值,value=该数值的index。因此当数组中存在相同的两个数时,dict里始终只记录了一个index,测试case就会跑挂掉。要倒过来记录。

好了,上代码,

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        #dict
        nums_dict=[(idx, nums[idx]) for idx in range(len(nums))]
        #nums_dict = {}
        #for idx in range(len(nums)):
        #    nums_dict[idx]=nums[idx]

        #sort nums by value
        nums_dict = sorted(nums_dict.items(), key=lambda item:item[1])

        #two idxs
        min_idx=0
        max_idx=len(nums)-1
        find = False
        while (min_idx < max_idx):
            curr_sum = nums_dict[min_idx][1] + nums_dict[max_idx][1]
            if curr_sum == target:
                find = True
                break
            elif curr_sum > target:
                max_idx -= 1
            elif curr_sum < target:
                min_idx += 1
        if find:
            return [nums_dict[min_idx][0], nums_dict[max_idx][0]]
        else:
            return []
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值