18. 4Sum
2016-03-15 15:34
190 查看
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.
跟之前的 2Sum, 3Sum 和 3Sum Closest 一样的做法,先排序,再左右夹逼,复杂度 O(n^3)
先求出每两个数的和,放到
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)
跟之前的 2Sum, 3Sum 和 3Sum Closest 一样的做法,先排序,再左右夹逼,复杂度 O(n^3)
先求出每两个数的和,放到
HashSet里,再利用之前的 2Sum 去求。这种算法比较快,复杂度 O(nnlog(n)),不过细节要处理的不少。
public class Solution { public List<List<Integer>> fourSum(int[] num, int target) { List<List<Integer>> ret = new ArrayList<List<Integer>>(); HashMap<Integer, List<Integer[]>> hm = new HashMap<Integer, List<Integer[]>>(); int len = num.length; Arrays.sort(num); // store pair for (int i = 0; i < len - 1; ++i) { for (int j = i + 1; j < len; ++j) { int sum = num[i] + num[j]; Integer[] tuple = {num[i], i, num[j], j}; if (!hm.containsKey(sum)) { hm.put(sum, new ArrayList<Integer[]>()); } hm.get(sum).add(tuple); } } Integer[] keys = hm.keySet().toArray(new Integer[hm.size()]); for (int key : keys) { if (hm.containsKey(key)) { if (hm.containsKey(target - key)) { List<Integer[]> first_pairs = hm.get(key); List<Integer[]> second_pairs = hm.get(target - key); for (int i = 0; i < first_pairs.size(); ++i) { Integer[] first = first_pairs.get(i); for (int j = 0; j < second_pairs.size(); ++j) { Integer[] second = second_pairs.get(j); // check if (first[1] != second[1] && first[1] != second[3] && first[3] != second[1] && first[3] != second[3]) { List<Integer> ans = Arrays.asList(first[0], first[2], second[0], second[2]); Collections.sort(ans); if (!ret.contains(ans)) { ret.add(ans); } } } } hm.remove(key); hm.remove(target - key); } } } return ret; } }
相关文章推荐
- PHP实现返回JSON和XML的类分享
- C++中虚析构函数的作用
- 三级联动的地址选择器
- 将博客搬至CSDN
- R基础入门教程
- vs2010在64位系统下常见数据类型的字节数
- Android中WheelView代码分析笔记1(明天继续分析 >>>>>)
- iOS开发之UITextView,设置textView的行间距及placeholder
- Glide加载图片并实现图片缓存
- EasyDialog 源码简析
- 【堆栈应用一】一个数divided=几个最小质因数的乘积
- I2C分析及RX8025驱动编写
- 【leetcode】【189】Rotate Array
- RAID简单介绍和Linux如何搭建一个RAID
- 初识Ansible
- PhoneGap&Cordova
- JAVA线程知识点
- 是不是要这样讲
- RGB颜色查询对照表
- 两个有序数组相融合