Intersection of Three Sorted Arrays

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

思路:i, j, k 三指针,移动比max小的,然后比较;

class Solution {
    public List arraysIntersection(int[] arr1, int[] arr2, int[] arr3) {
        List list = new ArrayList();
        int i = 0, j = 0, k = 0;
        while(i < arr1.length && j < arr2.length && k < arr3.length) {
            if(arr1[i] == arr2[j] && arr2[j] == arr3[k]) {
                list.add(arr1[i]);
                i++;
                j++;
                k++;
                continue;
            }
            
            int max = Math.max(arr1[i], Math.max(arr2[j], arr3[k]));
            if(arr1[i] < max) {
                i++;
            }
            if(arr2[j] < max) {
                j++;
            }
            if(arr3[k] < max) {
                k++;
            }
        }
        return list;
    }
}

 

你可能感兴趣的:(Two,pointers)