LeetCode 4Sum (Two pointers)

题意

Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
给定一个数组,找出其中的四个数,使它们的和等于某个特定的数

解法

和2Sum以及3Sum一样,都是先排序然后遍历前面几个数,剩下的两个数用Two Pointers来找,能降低一个N的复杂度,这里复杂度为O(N^3)

这里采用了一种比3Sum这题里更简洁的判重方法,直接将选出的数用Map记录,每次选取前检查一次Map看是否存在。虽然效率有所牺牲,但是代码变得很简洁而且有高可读性,自认为有些时候这种交换是值得的。

class Solution
{
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target)
    {
	    vector<vector<int>>	rt;
	    map<vector<int>,bool>	map;

	    sort(nums.begin(),nums.end());

	    for(int i = 0;i < nums.size();i ++)
		    for(int j = i + 1;j < nums.size();j ++)
		    {
			    int k = j + 1;
			    int	l = nums.size() - 1;
			    while(k < l)
			    {
				    if(nums[i] + nums[j] + nums[k] + nums[l] == target)
				    {
					    vector<int>	temp = {nums[i],nums[j],nums[k],nums[l]};
					    if(map.find(temp) == map.end())
					    {
						    map[temp] = true;
						    rt.push_back(temp);
					    }
					    k ++;
				    }

				    else	if(nums[i] + nums[j] + nums[k] + nums[l] < target)
					    k ++;
				    else
					    l --;
			    }
		    }
	    return	rt;
        
    }
};
posted @   Decouple  阅读(214)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
点击右上角即可分享
微信分享提示