给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。
注意:答案中不可以包含重复的三元组。
0 <= nums.length <= 3000
−105 <= nums[i] <= 105
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/3sum 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
函数接口定义:
public static List<List<Integer>> threeSum(int[] nums)
裁判测试程序样例:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] array = new int[n];
for(int i = 0; i <n; i++)
array[i] = sc.nextInt();
List<List<Integer>> result = threeSum(array);
for(int i = 0; i < result.size(); i++){
List<Integer> list = result.get(i);
for(int j = 0; j < list.size(); j++)
System.out.print(list.get(j) + " ");
System.out.println();
}
}
/* 请在这里填写答案 */
输入样例1:
第一行输入数组长度n,第二行输入数组元素,以空格间隔
6
-1 0 1 2 -1 4
输出样例1:
每个三元组一行
-1 -1 2
-1 0 1
输入样例2:
第一行输入数组长度n,第二行输入数组元素,以空格间隔
0
输出样例2:
每个三元组一行
输入样例3:
第一行输入数组长度n,第二行输入数组元素,以空格间隔
1
0
输出样例3:
每个三元组一行
代码如下:
public static List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> lists = new ArrayList<>();
Arrays.sort(nums);
int length = nums.length;;
for (int i = 0; i < length - 2; i ++) {
int start = i + 1;
int end = length - 1;
while (start < end) {
int sum = nums[i] + nums[start] + nums[end];
if (sum == 0) {
List<Integer> list = new ArrayList<>();
list.add(nums[i]);
list.add(nums[start]);
list.add(nums[end]);
lists.add(list);
while (start < end && nums[start] == nums[start + 1]) {
start ++;
}
while (start < end && nums[end] == nums[end - 1]) {
end --;
}
while (start < end && nums[i] == nums[i + 1]) {
i ++;
}
start ++;
end --;
} else if (sum < 0) {
start ++;
} else if (sum > 0) {
end --;
}
}
}
return lists;
}