[LeetCode] Intersection of Two Arrays II 两个数组的交集II

声明:原题目转载自LeetCode,解答部分为原创

Problem :

Given two arrays, write a function to compute their intersection.

Example:
Given nums1 = [1, 2, 2, 1]nums2 = [2, 2], return [2, 2].

Note:

  • Each element in the result should appear as many times as it shows in both arrays.
  • The result can be in any order.
Solution :

        思路:判断交集,先排序,再用两个指针分别从头到尾指向两个数组的元素。与上一题不同的是,当两指针指向数值相同时,直接将数值push进sub容器, 并将两个指针指向下一位;当数值不等时,数值小的一方将指针指向下一位。重复以上操作直至其中一方数值比较完。

        代码如下:

#include
#include
#include
using namespace std;

void output(vector & temp)
{
	for(int i = 0 ; i < temp.size() ; i ++)
	{
		cout << temp[i] << " ";
	}
	cout << endl;
}

class Solution {
public:
    vector intersect(vector& nums1, vector& nums2) {
        sort(nums1.begin(), nums1.end());
        sort(nums2.begin(), nums2.end());
        vector sub;
        
        int point_1 = 0;
        int point_2 = 0;
        while(point_1 < nums1.size() && point_2 < nums2.size())
        {
        	if(nums1[point_1] == nums2[point_2])
        	{
        		if(!sub.empty())
        		{
        			int pre_size = sub.size();
        			int sub_num = sub[pre_size - 1];
        			if(sub_num != nums1[point_1])
        				sub.push_back(nums1[point_1]);
				}
				else
        			sub.push_back(nums1[point_1]);
        		point_1 ++;
        		point_2 ++;
        		continue;
        	}
        	else if(nums1[point_1] < nums2[point_2])
        	{
        		point_1 ++;
        		continue;
			}
			else
			{
				point_2 ++;
				continue;
			}
		}
		return sub;
    }
};

int main()
{
	vector text_1;
	vector text_2;
	vector sub;
	
	text_1.push_back(1);
	text_1.push_back(2);
	
	text_2.push_back(2);
	text_2.push_back(1);
	
	Solution text;
	sub = text.intersect(text_1, text_2);
	
	output(sub);
	
	return 0;	
}


你可能感兴趣的:(LeetCode,C++,leetcode,两个数组的交集)