java - 如何从 ArrayList 的 ArrayList 中删除重复的 ArrayList
问题描述
问题:给定一个包含 n 个整数的数组 S,S 中是否存在元素 a、b、c 使得 a + b + c = 0?在数组中找到所有唯一的三元组,其总和为零。
我的代码:
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 进行一些操作,以便我可以做到。
解决方案
AbstractList(ArrayList 扩展)的 equals 方法被定义为如果两个列表包含相同顺序的相同元素,则它们是相等的。那么最简单的方法是从流中获取不同的列表:
List<List<Integer>> list = new ArrayList<>();
list.add(Arrays.asList(-5, 1, 4));
list.add(Arrays.asList(-5, 1, 4));
list.add(Arrays.asList(-5, 4, 1));
list.add(Arrays.asList(-4, 0, 4));
list.add(Arrays.asList(-4, 0, 4));
list.add(Arrays.asList(-4, 0, 4));
List<List<Integer>> distinctLists = list.stream().distinct().collect(Collectors.toList());
System.out.println(distinctLists); // prints [[-5, 1, 4], [-5, 4, 1], [-4, 0, 4]]
推荐阅读
- c# - 如何从混合数据类型数组中仅提取一个数据类型值?
- javascript - 如何在混合字符串和数字javascript中获得两次并比较它们
- php - Laravel github 在 gitignore 中分支供应商文件
- android - Firebase Firestore 在我删除用户后保留用户
- java - mvn deploy 是否还将 pom.xml 安装/复制到远程仓库中?
- c# - 无法访问 Microsoft.SqlServer.Mangement.Smo.Agent.JobStep 的属性或方法
- javascript - 我如何确保该人拥有商店中的特定商品?
- c# - C# Sql Server 保存点
- javascript - 如何检查复制字体的字体样式或样式?
- applescript - AppleScript 错误 Can't make path into type alias