350. 两个数组的交集 II

350. 两个数组的交集 II

题目描述在这里插入图片描述

哈希映射实现

#pragma once
#include <iostream>
#include<vector>
#include<unordered_map>

using namespace std;


class Solution 
{
public:
	vector<int> intersect(vector<int>& nums1, vector<int>& nums2) 
	{
		//使用哈希表存储每个数字出现的次数。(一个数字在交集中出现的次数等于该数字在两个数组中出现次数的最小值)
		unordered_map<int, int> hashmap;
		//遍历第一个数组,并在哈希表中记录第一个数组中的每个数字以及对应出现的次数
		for (int key : nums1)
		{
			++hashmap[key];
		}
		//遍历第二个数组
		vector<int> intersection;
		for (int num : nums2) 
		{
			//如果在哈希表中存在这个数字, 则将该数字添加到答案
			if (hashmap.count(num)) 
			{
				intersection.push_back(num);
				//减少哈希表中该数字出现的次数
				--hashmap[num];
				//删除为不存在的元素
				if (hashmap[num] == 0)
				{
					hashmap.erase(num);
				}
			}
		}
		return intersection;
	}
};



int main()
{
	int arry1[] = { 4,9,5 };
	int arry2[] = { 9,4,9,8,5 };

	vector<int> nums1;
	vector<int> nums2;
	//不使用for循环进行遍历
	for (int num1 : arry1)
	{
		nums1.push_back(num1);
	}

	for (int num2 : arry2)
	{
		nums2.push_back(num2);
	}


	Solution S;
	vector<int> intersection;
	intersection = S.intersect(nums1, nums2);
	for (auto it = intersection.begin(); it != intersection.end(); it++)
	{
		cout << *it << " ";
	}
	cout << endl;


	system("pause");
	return 0;
}

运行结果

在这里插入图片描述

提交结果

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值