【发布时间】:2020-03-06 09:04:17
【问题描述】:
问题:给定一个包含 n 个整数的数组 S,S 中是否存在满足 a + b + c = 0 的元素 a、b、c? 查找数组中所有唯一的三元组,其总和为零。
我的代码:
public class Solution {
public ArrayList<ArrayList<Integer>> threeSum(ArrayList<Integer> A) {
ArrayList<ArrayList<Integer>> C = new ArrayList<ArrayList<Integer>>();
int n = A.size();
for(int i =0; i<n-2; i++){
for(int j=i+1; j<n-1; j++){
for(int k=j+1; k< n; k++){
int sum = A.get(i)+A.get(j)+A.get(k);
if(sum == 0){
ArrayList<Integer> temp = new ArrayList<Integer>();
temp.add(A.get(i));
temp.add(A.get(j));
temp.add(A.get(k));
C.add(temp);
}
}
}
}
return C;
}
}
所以 C 可能包含重复的 Arraylist,我的目标是从 C 中删除重复的 Arraylist
示例:C = [-5 1 4 ] [-5 1 4 ] [-5 1 4 ] [-5 4 1 ] [-4 0 4 ] [-4 0 4 ]
我的目标是 = [-5 1 4 ] [-5 4 1 ] [-4 0 4 ]
请给我一些方法来对 C 进行一些操作,以便我可以做到。
【问题讨论】:
-
尝试在问题中使用格式化代码以获得更好的答案。在文本中的某处重复语言
Java也可能会有所帮助。到目前为止,它只存在于标签中......
标签: java list arraylist integer set