首页 > 其他 > 详细

找出所有满足条件a + b + c = 0且不重复的三元组。

时间:2020-03-20 16:51:52      阅读:341      评论:0      收藏:0      [点我收藏+]

给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组。

注意:答案中不可以包含重复的三元组。

 

示例:

给定数组 nums = [-1, 0, 1, 2, -1, -4],

满足要求的三元组集合为:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

1、暴力解决
public static List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> list = new ArrayList<>();
if (nums == null || nums.length < 3) {
return list;
}
Arrays.sort(nums);
for (int i = 0; i < nums.length; i++) {
for (int j = i+1; j < nums.length; j++) {
for (int k = j+1; k < nums.length; k++) {
if (nums[i] + nums[j] + nums[k] == 0) {
list.add(Arrays.asList(nums[i], nums[j], nums[k]));
}
}
}
}
return list;
}
但是这样会超出时间限制,而且还没有进行去重
2、改进版数组遍历
public static List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> list = new ArrayList<>();
if(nums == null || nums.length < 3) return list;
// 先把数组中的所有数进行升序排序
Arrays.sort(nums);
for (int i = 0; i < nums.length ; i++) {
// 如果当前要计算的第一个数字大于0,则其之后的数字一定大于0(因为已经排序了),所以三数之和一定大于0,结束循环
if(nums[i] > 0) {break;}
// 对三个数中的第一个数字去重
if(i > 0 && nums[i] == nums[i-1]) {continue;}
// 第二个数下标地址
int L = i+1;
// 第三个数下标地址
int R = nums.length-1;
// 当第二个数地址L在第三个数地址R前边的时候,遍历所有情况
while(L < R){
int sum = nums[i] + nums[L] + nums[R];
if(sum == 0){
list.add(Arrays.asList(nums[i],nums[L],nums[R]));
// 对三个数字中的第二个数去重
while (L<R && nums[L] == nums[L+1]) {L++;}
// 对三个数中的第三个数去重
while (L<R && nums[R] == nums[R-1]) {R--;}
//当sum==0时,第一个数保持不变的情况下,第二和第三个数不能再重复了,所以左边的L向后继续编遍历,右边的R向前继续遍历
L++;
R--;
}
// 当sum<0说明左边的数num[L]太小了,所以要左边的地址+1继续向后遍历
else if (sum < 0) {L++;}
// 当sum>0说明右边的数num[R]太大了,所以要右边的地址-1继续向前遍历
else if (sum > 0) {R--;}
}
}
return list;
}

找出所有满足条件a + b + c = 0且不重复的三元组。

原文:https://www.cnblogs.com/cdlyy/p/12532208.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!