LeetCode Intersection of Two Arrays

LeetCode Intersection of Two Arrays Given two arrays, write a function to compute their intersection. Example: Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2]. Note:

  • Each element in the result must be unique.
  • The result can be in any order.

本题要求两个数组的交集,注意题目要求,数组可以不满足集合性质,但是交集出来的结果必须满足集合的无序性、互异性、确定性。 这一题可以有太多的解法了,比如两个数组排个序,然后用类似归并排序的思路求交集;把一个数组hash到unordered_set里面,然后另一个数组去这个unordered_set找等。本题采用第二个思路,为了保证结果的互异性,使用了两个unordered_set,分别针对第一个集合和结果集合。完整代码如下: [cpp] class Solution { public: vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { vector<int> ans; unordered_set<int> s1, s_ans; for (int i = 0; i < nums1.size(); ++i) { s1.insert(nums1[i]); } for (int i = 0; i < nums2.size(); ++i) { if (s1.find(nums2[i]) != s1.end()) { s_ans.insert(nums2[i]); } } unordered_set<int>::iterator it = s_ans.begin(); while (it != s_ans.end()) { ans.push_back(*it); ++it; } return ans; } }; [/cpp] 本代码提交AC,用时12MS。]]>

1 thought on “LeetCode Intersection of Two Arrays

  1. Pingback: LeetCode Intersection of Two Arrays II | bitJoy > code

Leave a Reply

Your email address will not be published. Required fields are marked *