【leetcode刷题笔记】4Sum
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:
- Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
- The solution set must not contain duplicate quadruplets.
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)
题解:参考3Sum,把4Sum问题转换成3Sum,再转换成2Sum,如下图所示:
代码如下:
1 public class Solution { 2 public List<List<Integer>> fourSum(int[] num, int target) { 3 List<List<Integer>> answer = new ArrayList<List<Integer>>(); 4 if(num == null || num.length == 0) 5 return answer; 6 7 Arrays.sort(num); 8 int length = num.length; 9 for(int i = 0;i < length;i++){ 10 if(i!=0 && num[i]== num[i-1] ) 11 continue; 12 for(int j = i+1;j < length;j++ ){ 13 if(j != i+1 && num[j] == num[j-1] ) 14 continue; 15 int start = j + 1; 16 int last = length - 1; 17 while(start < last){ 18 int sum = num[i]+num[j]+num[start]+num[last]; 19 if(sum == target){ 20 ArrayList<Integer> result = new ArrayList<Integer>(); 21 result.add(num[i]); 22 result.add(num[j]); 23 result.add(num[start]); 24 result.add(num[last]); 25 answer.add(result); 26 start++; 27 last--; 28 while(start < last && num[start-1] == num[start]) 29 start++; 30 } 31 else if(sum < target){ 32 start++; 33 } 34 else { 35 last--; 36 } 37 } 38 } 39 } 40 return answer; 41 } 42 }
分类:
leetcode刷题总结
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了