Skip to content

Latest commit

 

History

History
166 lines (132 loc) · 3.8 KB

File metadata and controls

166 lines (132 loc) · 3.8 KB

English Version

题目描述

给出三个均为 严格递增排列 的整数数组 arr1arr2 和 arr3。返回一个由 在这三个数组中 同时出现 的整数所构成的有序数组。

 

示例 1:

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

示例 2:

输入: arr1 = [197,418,523,876,1356], arr2 = [501,880,1593,1710,1870], arr3 = [521,682,1337,1395,1764]
输出: []

 

提示:

  • 1 <= arr1.length, arr2.length, arr3.length <= 1000
  • 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
}

...