首页 > 解决方案 > 如何从 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 进行一些操作,以便我可以做到。

标签: javalistarraylistintegerset

解决方案


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]]

推荐阅读