【问题标题】:How to remove duplicates ArrayList from an ArrayList of ArrayList如何从 ArrayList 的 ArrayList 中删除重复的 ArrayList
【发布时间】: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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2018-05-29
    • 2014-03-25
    • 2015-12-12
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    • 2016-07-08
    相关资源
    最近更新 更多