[LeetCode] 18. 4Sum
Description
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.
Note: The solution set must not contain duplicate quadruplets.
1 2 3 4 5 6 7 8 | For example, given array S = [ 1 , 0 , - 1 , 0 , - 2 , 2 ], and target = 0 . A solution set is: [ [- 1 , 0 , 0 , 1 ], [- 2 , - 1 , 1 , 2 ], [- 2 , 0 , 0 , 2 ] ] |
思路
题意:给出一串整数值序列,输出a + b + c + d = target的方案
题解:此题与3Sum类似,区别在于这是求取四个数的和等于目标值的方案,因此将其降维为求取3Sum问题。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | class Solution { //61ms public List<List<Integer>> fourSum( int [] nums, int target) { Arrays.sort(nums); List<List<Integer>>res = new ArrayList<>(); int len = nums.length; for ( int i = 0 ;i < len - 3 ;i++){ threeSum(nums,nums[i],target - nums[i],i + 1 ,len,res); while (i + 1 < len && nums[i + 1 ] == nums[i]){ i++; } } return res; } public void threeSum( int [] nums, int val, int target, int lo, int ro,List<List<Integer>>res) { for ( int i = lo;i < ro - 2 ;i++){ int left = i + 1 ,right = ro - 1 ; int sum = target - nums[i]; while (left < right){ if (nums[left] + nums[right] < sum){ left++; } else if (nums[left] + nums[right] > sum){ right--; } else { res.add(Arrays.asList(val,nums[i],nums[left],nums[right])); while (++left < right && nums[left] == nums[left - 1 ]){} while (--right > left && nums[right] == nums[right + 1 ]){} } } while (i + 1 < ro - 2 && nums[i + 1 ] == nums[i]){ i++; } } } } |
┆ 凉 ┆ 暖 ┆ 降 ┆ 等 ┆ 幸 ┆ 我 ┆ 我 ┆ 里 ┆ 将 ┆ ┆ 可 ┆ 有 ┆ 谦 ┆ 戮 ┆ 那 ┆ ┆ 大 ┆ ┆ 始 ┆ 然 ┆
┆ 薄 ┆ 一 ┆ 临 ┆ 你 ┆ 的 ┆ 还 ┆ 没 ┆ ┆ 来 ┆ ┆ 是 ┆ 来 ┆ 逊 ┆ 没 ┆ 些 ┆ ┆ 雁 ┆ ┆ 终 ┆ 而 ┆
┆ ┆ 暖 ┆ ┆ 如 ┆ 地 ┆ 站 ┆ 有 ┆ ┆ 也 ┆ ┆ 我 ┆ ┆ 的 ┆ 有 ┆ 精 ┆ ┆ 也 ┆ ┆ 没 ┆ 你 ┆
┆ ┆ 这 ┆ ┆ 试 ┆ 方 ┆ 在 ┆ 逃 ┆ ┆ 会 ┆ ┆ 在 ┆ ┆ 清 ┆ 来 ┆ 准 ┆ ┆ 没 ┆ ┆ 有 ┆ 没 ┆
┆ ┆ 生 ┆ ┆ 探 ┆ ┆ 最 ┆ 避 ┆ ┆ 在 ┆ ┆ 这 ┆ ┆ 晨 ┆ ┆ 的 ┆ ┆ 有 ┆ ┆ 来 ┆ 有 ┆
┆ ┆ 之 ┆ ┆ 般 ┆ ┆ 不 ┆ ┆ ┆ 这 ┆ ┆ 里 ┆ ┆ 没 ┆ ┆ 杀 ┆ ┆ 来 ┆ ┆ ┆ 来 ┆
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)