热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

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

文章目录1.题目2.解题2.1哈希查找2.2位运算1.题目给你三个整数数组nums1、nums2和nums3,请你构造并返回一个不同数组,且由至少在两


文章目录

    • 1. 题目
    • 2. 解题
      • 2.1 哈希查找
      • 2.2 位运算


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;
Michael阿明


推荐阅读
author-avatar
杨静怡崇志
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有