Finding common elements in two arrays of different size

后端 未结 10 860
隐瞒了意图╮
隐瞒了意图╮ 2020-12-14 18:08

I have a problem to find common elements in two arrays and that\'s of different size.

Take , Array A1 of size n and Array A2 o

10条回答
  •  萌比男神i
    2020-12-14 18:51

    Try heapifying both arrays followed by a merge to find the intersection.

    Java example:

    public static >List intersection(Collection c1,
                                                                Collection c2) {
        List result = new ArrayList();
        PriorityQueue q1 = new PriorityQueue(c1),
                         q2 = new PriorityQueue(c2);
        while (! (q1.isEmpty() || q2.isEmpty())) {
            E e1 = q1.peek(), e2 = q2.peek();
            int c = e1.compareTo(e2);
            if (c == 0) result.add(e1);
            if (c <= 0) q1.remove();
            if (c >= 0) q2.remove();
        }
        return result;
    }
    

    See this question for more examples of merging.

提交回复
热议问题