作者:杨静怡崇志 | 来源:互联网 | 2023-09-13 13:03
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 <&#61; nums1.length, nums2.length, nums3.length <&#61; 100
1 <&#61; nums1[i], nums2[j], nums3[k] <&#61; 100
来源&#xff1a;力扣&#xff08;LeetCode&#xff09; 链接&#xff1a;https://leetcode-cn.com/problems/two-out-of-three
著作权归领扣网络所有。商业转载请联系官方授权&#xff0c;非商业转载请注明出处。
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)!&#61;s2.end() || s3.find(n)!&#61;s3.end())ans.insert(n);}for(auto n : nums2){if(s1.find(n)!&#61;s1.end() || s3.find(n)!&#61;s3.end())ans.insert(n);}return vector<int> (ans.begin(), ans.end());}
};
20 ms 26.5 MB C&#43;&#43;
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] |&#61; 1;for(auto n : nums2)state[n] |&#61; 2;for(auto n : nums3)state[n] |&#61; 4;for(int i &#61; 1; i < 101; &#43;&#43;i){if(state[i]&#61;&#61;3 || state[i]&#61;&#61;6 || state[i]&#61;&#61;5 || state[i]&#61;&#61;7)ans.push_back(i);}return ans;}
};
8 ms 24.5 MB C&#43;&#43;
我的CSDN博客地址 https://michael.blog.csdn.net/
长按或扫码关注我的公众号&#xff08;Michael阿明&#xff09;&#xff0c;一起加油、一起学习进步&#xff01;