Intersection of Two Arrays II Medium

Algorithm twenty days

the eleventh day

The intersection of two arrays II
gives you two integer arrays nums1 and nums2, please return the intersection of the two arrays as an array. The number of occurrences of each element in the returned result should be consistent with the number of occurrences of the element in both arrays (if the number of occurrences is inconsistent, consider taking a smaller value). The order of the output results can be ignored.

Example 1:

Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]

Example 2:

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9]

hint:

1 <= nums1.length, nums2.length <= 1000
0 <= nums1[i],
nums2[i] <=1000

Advanced:

What if the given array is already sorted? How would you optimize your algorithm?
Which method is better if nums1 is smaller than nums2?
What do you do if the elements of nums2 are stored on disk, memory is limited, and you cannot load all elements into memory at once?

Author: LeetCode
Link: https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/x2y0c2/

#include<bits/stdc++.h>
using namespace std; 
//法一:利用map计数
 /*vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
	int map[1001]={0};//所有可能的数
	vector<int> temp;
	for(int i=0;i<nums1.size();i++)
		map[nums1[i]]++;
	for(int i=0;i<nums2.size();i++)
		if(map[nums2[i]])//遍历有重复的就push进temp;
		{
			map[nums2[i]]--;
			temp.push_back(i);
		}
	return temp;
}*/

vector<int> intersect(vector<int>& nums1, vector<int>& nums2)
{
    
    
	sort(nums1.begin(),nums1.end());
	sort(nums2.begin(),nums2.end());
	//排序
	int i=0,j=0;
	vector<int> temp;
	while(i<nums1.size()&&j<nums2.size())
	{
    
    
		if(nums1[i]<nums2[j])
			i++;
		else if(nums1[i]>nums2[j])
				j++;
		else
		{
    
    
			temp.push_back(nums1[i]);
			i++;
			j++;
		}
			
	}
	return temp;
	
}

int main()
{
    
    
	vector<int> temp1={
    
    1,1};
	vector<int> temp2={
    
    1,2};
	vector<int> temp3=intersect(temp1,temp2);
	for(auto &o:temp3)
		cout<<o<<" ";
}

For nums2 that cannot come in all at once, I can only think of using the n^2 method to compare one by one

Guess you like

Origin blog.csdn.net/BeiWoFW/article/details/124308119