lintcode-- 四数之和
来源:互联网 发布:手机上怎么看淘宝分销 编辑:程序博客网 时间:2024/05/24 03:28
给一个包含n个数的整数数组S,在S中找到所有使得和为给定整数target的四元组(a, b, c, d)。
注意事项
四元组(a, b, c, d)中,需要满足a <= b <= c <= d
答案中不可以包含重复的四元组。
例如,对于给定的整数数组S=[1, 0, -1, 0, -2, 2] 和 target=0. 满足要求的四元组集合为:
(-1, 0, 0, 1)
(-2, -1, 1, 2)
(-2, 0, 0, 2)
/*
思路:
先排序,先用嵌套循环指定前两个元素,然后二分法确定后两个元素。
*/
public class Solution {
public ArrayList<ArrayList<Integer>> fourSum(int[] num, int target) {
ArrayList<ArrayList<Integer>> rst = new ArrayList<ArrayList<Integer>>();
Arrays.sort(num);//先排序
for (int i = 0; i < num.length - 3; i++) {//-3
if (i != 0 && num[i] == num[i - 1]) {
continue;//重复则跳过
}
for (int j = i + 1; j < num.length - 2; j++) {//-2
if (j != i + 1 && num[j] == num[j - 1])
continue;//重复则跳过
int left = j + 1;//j+1
int right = num.length - 1;
while (left < right) {
int sum = num[i] + num[j] + num[left] + num[right];
if (sum < target) {
left++;
} else if (sum > target) {
right--;
} else {
ArrayList<Integer> tmp = new ArrayList<Integer>();
tmp.add(num[i]);
tmp.add(num[j]);
tmp.add(num[left]);
tmp.add(num[right]);
rst.add(tmp);
//在sum==target 的时候left和right 需要变化,多个集合满足
left++;
right--;
//重复则跳过
while (left < right && num[left] == num[left - 1]) {
left++;
}
while (left < right && num[right] == num[right + 1]) {
right--;
}
}
}
}
}
return rst;
}
}
- lintcode-- 四数之和
- lintcode(58)四数之和
- LintCode两数之和,三数之和,四数之和
- 【lintcode】两数之和、三数之和、最接近的三数之和、四数之和小结
- Lintcode 两数之和
- LintCode 三数之和
- LintCode 两数之和
- LintCode 三数之和
- LintCode: 三数之和
- lintcode,三数之和
- Lintcode 三数之和
- LintCode-两数之和
- LintCode 两数之和
- lintcode--两数之和
- [Lintcode]三数之和
- lintcode--三数之和
- lintcode 两数之和
- lintcode 三数之和
- Prim算法
- Ubuntu17.04搭建Shadowsocks
- QListWidget使用整理
- 从input tap来看事件注入的调用流程
- 关于xml的规范
- lintcode-- 四数之和
- 湖南省第九届大学生计算机程序设计竞赛 好老师
- linux下离线安装mysql
- OpenJudge-49:计算对数
- 解决record is locked by another user
- Kruskal算法(不能运行)
- Android-auto-android-car崛起-黑莓的QNX在汽车领域的未来将如何
- 【贪心】qbxt精英班
- 浙工大姗姗杯round2 CodeForces 116BLittle Pigs and Wolves