Hash Table -- Leetcode problem349. Intersection of Two Arrays

来源:互联网 发布:foxmail邮件导入到mac 编辑:程序博客网 时间:2024/06/05 18:53
  • 描述: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.

  • 分析:这道题是找出两个数组中的重复元素之后输出,要求输出无重复。
  • 思路一:用unordered_map来进行比较操作
class Solution {public:    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {    vector<int> my_vec;    unordered_map<int, int> my_map;    for (int i = 0; i < nums1.size(); i++) {        my_map[nums1[i]] = 0;    }    for (int i = 0; i < nums2.size(); i++) {        if (my_map.find(nums2[i]) != my_map.end()) {            my_vec.push_back(nums2[i]);            my_map.erase(nums2[i]);        }    }    return my_vec;}};
阅读全文
0 0
原创粉丝点击