力扣(十六) 最接近的三数之和

本文介绍了一个寻找数组中三个数之和最接近给定目标值的高效算法。通过先排序再使用双指针技巧,实现O(n^2)时间复杂度的解决方案。该算法能有效处理重复元素,确保找到最优解。

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

题目描述
在这里插入图片描述
解题
同上一题,改变判断标准即可。

public int ThreeSumClosest(int[] nums, int target) {
			int result = nums[0] + nums[1] + nums[2];
            int distance = Math.Abs(target - result);
            Array.Sort(nums);
            for (int i = 0; i < nums.Length - 2 ; i++)
            {
                if (i > 0 && nums[i] == nums[i - 1]) continue;
                int L = i + 1;
                int R = nums.Length - 1;
                int sum = nums[i] + nums[L] + nums[R];
                while (L < R)
                {
                    sum = nums[i] + nums[L] + nums[R];
                    if (sum == target) return sum;
                    else
                    {
                        if (Math.Abs(target - sum) < distance)
                        {
                            result = sum;
                            distance = Math.Abs(target - sum);
                        }
                        else if (sum < target)
                        {
                            L++;
                        }else R--;
                    }               
                }
            }
            return result;
    }
### LeetCode 两数之和 (Two Sum) 的 C++ 实现 #### 使用哈希表的方法 为了高效解决这个问题,可以利用 `std::unordered_map` 来存储已经遍历过的数值及其索引位置。这种方法的时间复杂度接近 O(n),因为平均情况下查找、插入操作都是常量时间。 ```cpp class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { unordered_map<int, int> numMap; for (int i = 0; i < nums.size(); ++i){ int complement = target - nums[i]; if (numMap.find(complement) != numMap.end()){ return {numMap[complement], i}; } numMap[nums[i]] = i; } throw invalid_argument("No two sum solution"); } }; ``` 此方法通过单次遍历输入列表来完成任务,在每次迭代过程中检查当前元素所需补数是否已存在于映射中[^2]。如果存在,则立即返回这两个下标的组合;否则将当前元素加入到映射里以便后续可能匹配使用。 #### 排序双指针法 另一种常见的解法是先对原数组进行排序再采用双向指针的方式寻找目标值。不过需要注意的是题目要求返回原始未排序前的索引值,因此需要额外保存一份原始数据的位置信息。 ```cpp class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { int n = nums.size(); pair<int,int> sortedNums[n]; for(int i=0;i<n;++i) sortedNums[i]=make_pair(nums[i],i); sort(sortedNums,sortedNums+n); int l=0,r=n-1; while(l<r){ int s=sortedNums[l].first+sortedNums[r].first; if(s==target)return{sortedNums[l].second,sortedNums[r].second}; if(s<target)l++; else r--; } return {}; } }; ``` 上述代码首先创建了一个由数值与其对应初始索引组成的配对数组,并对其进行升序排列。接着运用两个游标分别指向首尾两端向中间靠拢直到找到满足条件的一组数字并输出其原本所在位置[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值