Intersection and union of ArrayLists in Java

后端 未结 24 2177
离开以前
离开以前 2020-11-22 06:05

Are there any methods to do so? I was looking but couldn\'t find any.

Another question: I need these methods so I can filter files. Some are AND filter

24条回答
  •  清酒与你
    2020-11-22 06:41

    The solution marked is not efficient. It has a O(n^2) time complexity. What we can do is to sort both lists, and the execute an intersection algorithm as the one below.

    private  static ArrayList interesect(ArrayList f, ArrayList s) { 
        ArrayList res = new ArrayList();
    
        int i = 0, j = 0; 
        while (i != f.size() && j != s.size()) { 
    
            if (f.get(i) < s.get(j)) {
                i ++;
            } else if (f.get(i) > s.get(j)) { 
                j ++;
            } else { 
                res.add(f.get(i)); 
                i ++;  j ++;
            }
        }
    
    
        return res; 
    }
    

    This one has a complexity of O(n log n + n) which is in O(n log n). The union is done in a similar manner. Just make sure you make the suitable modifications on the if-elseif-else statements.

    You can also use iterators if you want (I know they are more efficient in C++, I dont know if this is true in Java as well).

提交回复
热议问题