GuilinDev

Lc1213

05 August 2008

1213. Intersection of Three Sorted Arrays

给定三个按严格递增顺序排序的整数数组 arr1、arr2 和 arr3,返回仅包含所有三个数组中出现的整数的排序数组。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
    public List<Integer> arraysIntersection(int[] arr1, int[] arr2, int[] arr3) {
        List<Integer> results = new ArrayList<>();
        int p1 = 0, p2 = 0, p3 = 0;
        while (p1 < arr1.length && p2 < arr2.length && p3 < arr3.length) {
            int cand1 = arr1[p1], cand2 = arr2[p2], cand3 = arr3[p3];
            int min = Math.min(cand1, Math.min(cand2, cand3));
            if (cand1 == cand2 && cand2 == cand3) {
                results.add(cand1);
                p1++;
                p2++;
                p3++;
            } else {
                if (min == cand1) {
                    p1++;
                } else if (min == cand2) {
                    p2++;
                } else {
                    p3++;
                }
            }
        }

        return results;
    }
}