四数之和——LinkCode
2015-12-14 19:08
246 查看
给一个包含n个数的整数数组S,在S中找到所有使得和为给定整数target的四元组(a, b, c, d)。
您在真实的面试中是否遇到过这个题?
Yes
样例
例如,对于给定的整数数组S=[1, 0, -1, 0, -2, 2]和 target=0. 满足要求的四元组集合为:
(-1, 0, 0, 1)
(-2, -1, 1, 2)
(-2, 0, 0, 2)
注意
四元组(a, b, c, d)中,需要满足a <= b <= c <= d
答案中不可以包含重复的四元组。
您在真实的面试中是否遇到过这个题?
Yes
样例
例如,对于给定的整数数组S=[1, 0, -1, 0, -2, 2]和 target=0. 满足要求的四元组集合为:
(-1, 0, 0, 1)
(-2, -1, 1, 2)
(-2, 0, 0, 2)
注意
四元组(a, b, c, d)中,需要满足a <= b <= c <= d
答案中不可以包含重复的四元组。
public class Solution { /** * @param numbers : Give an array numbersbers of n integer * @param target : you need to find four elements that's sum of target * @return : Find all unique quadruplets in the array which gives the sum of * zero. */ public ArrayList<ArrayList<Integer>> fourSum(int[] numbers, int target) { /* your code */ Arrays.sort(numbers); int len = 0; if(target >= 0) { for(int i=0;i<numbers.length;i++) if(numbers[i] >= target) { len = i; break; } } else { len = numbers.length-1; } ArrayList<ArrayList<Integer>> arrayList = new ArrayList<>(); for(int i=0;i<=len;i++) for(int j=i+1;j<numbers.length;j++) for(int k=j+1;k<numbers.length;k++) for(int h=k+1;h<numbers.length;h++) { if(numbers[h]+numbers[i] + numbers[j] + numbers[k] == target) { ArrayList<Integer> list = new ArrayList<>(); int[] x = {numbers[i],numbers[j],numbers[k],numbers[h]}; Arrays.sort(x);; list.add(x[0]); list.add(x[1]); list.add(x[2]); list.add(x[3]); if(arrayList.contains(list) == false) arrayList.add(list); break; } } return arrayList; } }
相关文章推荐
- 4、应用程序设置应用程序详细信息页面
- POJ3984 迷宫问题 BFS记录路径
- P2P-BT对端管理协议(附BT协议1.0)
- Android Studio 多渠道打包(三)
- [算法]归并排序
- 数据库选取之路
- POJ1742Coins(多重背包)
- 堆排序
- Linux增加系统调用
- HQL语法与详细解释[整理]
- 每个人都有自己的机缘,看别人的风景,品自己的人生!
- cubieboard apt-get 软件安装不了
- wordcloud(词云)
- 小马哥----高仿机部分6735芯片机型的root方法浅析 高仿三星Galaxy S6 A228_4G刷机root
- centOS6.4 oracle11g RAC搭建
- 字符串答疑
- 第八周项目1 建立顺序串的算法库
- More Effective C++ 第一部分 基础议题
- HashMap数据类型使用注意
- 获取鼠标的坐标位置