MENU

LeetCode349. Intersection of Two Arrays(模拟)

2019 年 02 月 14 日 • 阅读: 875 • LeetCode阅读设置

LeetCode349. Intersection of Two Arrays(模拟)

  • Easy
  • Accepted:192,087
  • Submissions:365,725

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

Example 1:

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

Example 2:

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

Note:

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

链接

https://leetcode.com/problems/intersection-of-two-arrays/

题意

给定两个数组,找出它们的交集。集合中元素唯一,顺序可以不同。

题解

  • 直接模拟,用个set就好了,写法多种多样,解锁set使用新姿势

代码

  • Runtime: 12 ms, faster than 89.15% of C++ online submissions for Intersection of Two Arrays.
  • Memory Usage: 9.4 MB, less than 100.00% of C++ online submissions for Intersection of Two Arrays.
class Solution {
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        int n = nums1.size(), m = nums2.size();
        set <int> st;
        vector <int> vt;
        for (int i = 0; i < n; ++i)
            st.insert(nums1[i]);
        // set <int> st(nums1.begin(), nums1.end());
        // vector <int> vt(st.begin(), st.end());
        for (int i = 0; i < m; ++i) 
        {
             // st.find(x) != st.end()
             if (st.count(nums2[i]) > 0) // 存在
             {
                vt.push_back(nums2[i]);  
                st.erase(nums2[i]); // 去重
             }
        }
        return vt;
    }
};

The end.
2019年2月14日 星期四