[英]How to remove duplicates ArrayList from an ArrayList of 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,我的目標是從 Z0D61F8816C2CB92B12F24A568025B749E5Z 中刪除重復的 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 的 equals 方法(ArrayList 擴展)被定義為如果兩個列表包含相同順序的相同元素,則它們是相等的。 最簡單的方法是從 stream 中獲取不同的列表:
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]]
As given in previous answer, create a list of list
List<List<Integer>> listToBeUpdated = 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));
然后,您可以使用 Set 實現此目的(因為 set 不允許重復)。 在 Java 8 中:
listToBeUpdated.stream().flatMap(List::stream).collect(Collectors.toSet())
或者您可以簡單地:
public List<Integer> removeDuplicatesFromList(List<List<Integer>> listToBeUpdated) {
Set<Integer> uniqueList = new HashSet<Integer>(); //Use TreeSet<Integer>, for sorting order or LinkedHashSet<Integer> for insertion order
for(List<Integer> anInt: list) {
uniques.addAll(anInt);
}
return new ArrayList<>(uniqueList); // If you want to return list
}
Hope it helps !
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.