LeetCode 1213. Intersection of Three Sorted Arrays

Posted Dylan_Java_NYC

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 1213. Intersection of Three Sorted Arrays相关的知识,希望对你有一定的参考价值。

原题链接在这里:https://leetcode.com/problems/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

题解:

Have 3 pointers pointing to 3 arrays.

If 3 pointed values are the same, add it to res and move all 3 pointers.

Else if first value < second value, move 1st pointer.

Else if second value < third value, now first value must be >= second value, need to move 2nd pointer.

Else move the 3rd pointer, since noew first value >= second value and second value >= third value.

Time Complexity: O(n). n = sum of array lengths.

Space: O(1).

AC Java:

 1 class Solution {
 2     public List<Integer> arraysIntersection(int[] arr1, int[] arr2, int[] arr3) {
 3         List<Integer> res = new ArrayList<>();
 4         if(arr1 == null || arr2 == null || arr3 == null){
 5             return res;
 6         }
 7         
 8         int i = 0;
 9         int j = 0;
10         int k = 0;
11         while(i < arr1.length && j < arr2.length && k < arr3.length){
12             if(arr1[i] == arr2[j] && arr1[i] == arr3[k]){
13                 res.add(arr1[i]);
14                 i++;
15                 j++;
16                 k++;
17             }else if(arr1[i] < arr2[j]){
18                 i++;
19             }else if(arr2[j] < arr3[k]){
20                 j++;
21             }else{
22                 k++;
23             }
24         }
25         
26         return res;
27     }
28 }

类似Intersection of Two Arrays.

以上是关于LeetCode 1213. Intersection of Three Sorted Arrays的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 1213:整数转罗马数字-罗马数字转整数

LeetCode:Intersection of Two Arrays

LeetCode:Intersection of Two Linked Lists

[LeetCode] Intersection of Two Arrays II

[leetcode]349.Intersection of Two Arrays

LeetCode:Intersection of Two Arrays II