18. 四数之和 4Sum
Given an array nums
of n integers and an integer target
, are there elements a, b, c, and d in nums
such that a + b + c+ d = target
? Find all unique quadruplets in the array which gives the sum of target
.
Notice that the solution set must not contain duplicate quadruplets.
Input: nums = [1,0,-1,0,-2,2], target = 0
Output: [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
方法类似于三数相加
也是双指针,有些情况可以优化,比如最前四个相加大于target可以退出,最后四个相加小于target可以退出。再就是去掉重复的。
public List<List<Integer>> fourSum(int[] nums, int target) { List<List<Integer>> ans = new ArrayList<>(); int n = nums.length; if (n < 4) { return ans; } Arrays.sort(nums); for (int first = 0; first < n - 3; first++) { if (nums[first] + nums[first + 1] + nums[first + 2] + nums[first + 3] > target) break; if (nums[first] + nums[n - 3] + nums[n - 2] + nums[n - 1] < target) continue; if (first > 0 && nums[first] == nums[first - 1]) { continue; } for (int second = first + 1; second < n - 2; second++) { if (nums[first] + nums[second] + nums[second + 1] + nums[second + 2] > target) break; if (nums[first] + nums[second] + nums[n - 2] + nums[n - 1] < target) continue; if (second > first + 1 && nums[second] == nums[second - 1]) { continue; } int forth = n - 1; for (int third = second + 1; third < forth; ) { int sum = nums[first] + nums[second] + nums[third] + nums[forth]; if (sum == target) { List<Integer> ans_one = new ArrayList<>(); ans_one.add(nums[first]); ans_one.add(nums[second]); ans_one.add(nums[third]); ans_one.add(nums[forth]); ans.add(ans_one); while (third < forth && nums[third] == nums[third + 1]) { third++; } third++; while (third < forth && nums[forth] == nums[forth - 1]) { forth--; } forth--; } else if (sum < target) { third++; } else { forth--; } } } } return ans; }
参考链接:
https://leetcode.com/problems/4sum/
https://leetcode-cn.com/problems/4sum/
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具