2032. 至少在两个数组中出现的值

给你三个整数数组 nums1nums2nums3 ,请你构造并返回一个 元素各不相同的 数组,且由 至少两个 数组中出现的所有值组成数组中的元素可以按 任意 顺序排列。

示例 1:

输入:nums1 = [1,1,3,2], nums2 = [2,3], nums3 = [3]
输出:[3,2]
解释:至少在两个数组中出现的所有值为:
- 3 ,在全部三个数组中都出现过。
- 2 ,在数组 nums1 和 nums2 中出现过。

示例 2:

输入:nums1 = [3,1], nums2 = [2,3], nums3 = [1,2]
输出:[2,3,1]
解释:至少在两个数组中出现的所有值为:
- 2 ,在数组 nums2 和 nums3 中出现过。
- 3 ,在数组 nums1 和 nums2 中出现过。
- 1 ,在数组 nums1 和 nums3 中出现过。

示例 3:

输入:nums1 = [1,2,2], nums2 = [4,3,3], nums3 = [5]
输出:[]
解释:不存在至少在两个数组中出现的值。

提示:

  • 1 <= nums1.length, nums2.length, nums3.length <= 100

  • 1 <= nums1[i], nums2[j], nums3[k] <= 100

题解

借鉴三角形,两边之和大于第三边

class Solution {
    public List<Integer> twoOutOfThree(int[] nums1, int[] nums2, int[] nums3) {
        int[] counts = new int[101];
        for(int i = 0 ; i < nums1.length; i++){
            int temp = counts[nums1[i]];
            if(temp < 2){
                counts[nums1[i]]+=2;
            }
        }
        for(int i = 0 ; i < nums2.length; i++){
            int temp = counts[nums2[i]];
            if(temp < 3){
                counts[nums2[i]]+=3;
            }
        }
        for(int i = 0 ; i < nums3.length; i++){
            int temp = counts[nums3[i]];
            if(temp < 4){
                counts[nums3[i]]+=4;
            }
        }
		// 防止扩容
        List<Integer> result = new ArrayList<>(151);
        for(int i = 0 ; i < 101; i++){
			// 这里
            if(counts[i] > 4){
                result.add(i);
            }
        }
        return result;
    }
}

优化

class Solution {
    public List<Integer> twoOutOfThree(int[] nums1, int[] nums2, int[] nums3) {
        List<Integer> result = new ArrayList<>();
        int[] counts = new int[101];
        for(int num: nums1){
            counts[num] = 2;
        }
        for(int num: nums2){
            int temp = counts[num];
            if(temp < 3){
                if(temp > 0){
                    result.add(num);
                }
                counts[num] = temp + 3;
            }
        }
        for(int num: nums3){
            int temp = counts[num];
            if(temp < 4){
                if(temp > 0){
                    result.add(num);
                }
                counts[num] = temp + 4;
            }
        }
        return result;
    }
}