LeetCode 2032. 至少在两个数组中出现的值(哈希/位运算)

简介: LeetCode 2032. 至少在两个数组中出现的值(哈希/位运算)

文章目录


1. 题目


给你三个整数数组 nums1、nums2 和 nums3 ,请你构造并返回一个 不同 数组,且由 至少 在 两个 数组中出现的所有值组成。

数组中的元素可以按 任意 顺序排列。

示例 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


2. 解题


2.1 哈希查找

class Solution {
public:
    vector<int> twoOutOfThree(vector<int>& nums1, vector<int>& nums2, vector<int>& nums3) {
        unordered_set<int> s1(nums1.begin(), nums1.end()), s2(nums2.begin(), nums2.end()), s3(nums3.begin(), nums3.end());
        unordered_set<int> ans;
        for(auto n : nums1)
        {
            if(s2.find(n)!=s2.end() || s3.find(n)!=s3.end())
                ans.insert(n);
        }
        for(auto n : nums2)
        {
            if(s1.find(n)!=s1.end() || s3.find(n)!=s3.end())
                ans.insert(n);
        }
        return vector<int> (ans.begin(), ans.end());
    }
};


20 ms 26.5 MB C++

2.2 位运算


  • 用3个二进制位表示每个数在三个数组里的状态是否存在
  • 检查状态的二进制值是否有2个以上的1
class Solution {
public:
    vector<int> twoOutOfThree(vector<int>& nums1, vector<int>& nums2, vector<int>& nums3) {
        vector<int> ans, state(101);
        for(auto n : nums1)
            state[n] |= 1;
        for(auto n : nums2)
            state[n] |= 2;
        for(auto n : nums3)
            state[n] |= 4;
        for(int i = 1; i < 101; ++i)
        {
            if(state[i]==3 || state[i]==6 || state[i]==5 || state[i]==7)
                ans.push_back(i);
        }
        return ans;
    }
};

8 ms 24.5 MB C++

相关文章
|
1月前
《LeetCode》—— 哈希
《LeetCode》—— 哈希
|
1月前
|
算法
【数组相关面试题】LeetCode试题
【数组相关面试题】LeetCode试题
|
1月前
|
存储
力扣面试经典题之数组/字符串
力扣面试经典题之数组/字符串
23 0
|
9天前
|
C++
【力扣】2562. 找出数组的串联值
【力扣】2562. 找出数组的串联值
|
1月前
|
存储 算法
《LeetCode 热题 HOT 100》——寻找两个正序数组的中位数
《LeetCode 热题 HOT 100》——寻找两个正序数组的中位数
|
1月前
|
存储
力扣刷题-最大子数组和
力扣刷题-最大子数组和
10 1
|
1月前
leetcode2967. 使数组成为等数数组的最小代价
leetcode2967. 使数组成为等数数组的最小代价
20 0
|
1月前
|
算法 搜索推荐
LeetCode刷题---215. 数组中的第K个最大元素(双指针,快速选择)
LeetCode刷题---215. 数组中的第K个最大元素(双指针,快速选择)
|
1月前
|
Go C++
【力扣】2645. 构造有效字符串的最小插入数(动态规划 贪心 滚动数组优化 C++ Go)
【2月更文挑战第17天】2645. 构造有效字符串的最小插入数(动态规划 贪心 滚动数组优化 C++ Go)
31 8
|
1月前
|
算法 测试技术 索引
力扣面试经典题之数组/字符串(二)
力扣面试经典题之数组/字符串(二)
13 0

热门文章

最新文章