Skip to content

Latest commit

 

History

History

1213.Intersection of Three Sorted Arrays

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 
 
 

English Version

题目描述

给出三个均为 严格递增排列 的整数数组 arr1arr2 和 arr3

返回一个由 在这三个数组中 同时出现 的整数所构成的有序数组。

 

示例:

输入: arr1 = [1,2,3,4,5], arr2 = [1,2,5,7,9], arr3 = [1,3,4,5,8]
输出: [1,5]
解释: 只有 1 和 5 同时在这三个数组中出现.

 

提示:

  1. 1 <= arr1.length, arr2.length, arr3.length <= 1000
  2. 1 <= arr1[i], arr2[i], arr3[i] <= 2000

解法

二分查找。

Python3

class Solution:
    def arraysIntersection(self, arr1: List[int], arr2: List[int], arr3: List[int]) -> List[int]:
        def find(arr, val):
            left, right = 0, len(arr) - 1
            while left < right:
                mid = (left + right) >> 1
                if arr[mid] >= val:
                    right = mid
                else:
                    left = mid + 1
            return arr[left] == val

        res = []
        for num in arr1:
            if find(arr2, num) and find(arr3, num):
                res.append(num)
        return res

Java

class Solution {
    public List<Integer> arraysIntersection(int[] arr1, int[] arr2, int[] arr3) {
        List<Integer> res = new ArrayList<>();
        for (int num : arr1) {
            if (find(arr2, num) && find(arr3, num)) {
                res.add(num);
            }
        }
        return res;
    }

    private boolean find(int[] arr, int val) {
        int left = 0, right = arr.length - 1;
        while (left < right) {
            int mid = (left + right) >> 1;
            if (arr[mid] >= val) {
                right = mid;
            } else {
                left = mid + 1;
            }
        }
        return arr[left] == val;
    }
}

C++

class Solution {
public:
    vector<int> arraysIntersection(vector<int>& arr1, vector<int>& arr2, vector<int>& arr3) {
        vector<int> res;
        for (int num : arr1) {
            if (find(arr2, num) && find(arr3, num)) {
                res.push_back(num);
            }
        }
        return res;
    }

private:
    bool find(vector<int>& arr, int val) {
        int left = 0, right = arr.size() - 1;
        while (left < right) {
            int mid = left + right >> 1;
            if (arr[mid] >= val) {
                right = mid;
            } else {
                left = mid + 1;
            }
        }
        return arr[left] == val;
    }
};

Go

func arraysIntersection(arr1 []int, arr2 []int, arr3 []int) []int {
	var res []int
	for _, num := range arr1 {
		if find(arr2, num) && find(arr3, num) {
			res = append(res, num)
		}
	}
	return res
}

func find(arr []int, val int) bool {
	left, right := 0, len(arr)-1
	for left < right {
		mid := (left + right) >> 1
		if arr[mid] >= val {
			right = mid
		} else {
			left = mid + 1
		}
	}
	return arr[left] == val
}

...