Thursday, October 8, 2020

LeetCode [1213] Intersection of Three Sorted Arrays

 1213. Intersection of Three Sorted Arrays

Easy

Given three integer arrays arr1arr2 and arr3 sorted in strictly increasing order, return a sorted array of only the integers that appeared in all three arrays.

 

Example 1:

Input: arr1 = [1,2,3,4,5], arr2 = [1,2,5,7,9], arr3 = [1,3,4,5,8]
Output: [1,5]
Explanation: Only 1 and 5 appeared in the three arrays.

 

Constraints:

  • 1 <= arr1.length, arr2.length, arr3.length <= 1000
  • 1 <= arr1[i], arr2[i], arr3[i] <= 2000
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
    public List<Integer> arraysIntersection(int[] arr1, int[] arr2, int[] arr3) {
        List<Integer> ret = new ArrayList<Integer>();
        int i1 = 0, i2 = 0, i3 = 0;

        while (i1 < arr1.length && i2 < arr2.length && i3 < arr3.length) {
            int v1 = arr1[i1], v2 = arr2[i2], v3 = arr3[i3];
            if (v1 == v2 && v2 == v3) {
                ret.add(v1);
                i1++;
                i2++;
                i3++;
            } else if (v1 <= v2 && v1 <= v3) {
                i1++;
            } else if (v2 <= v1 && v2 <= v3) {
                i2++;
            } else {
                i3++;
            }
        }

        return ret;
    }
}

No comments:

Post a Comment