leetcode_ntersection of Two Arrays

来源:互联网 发布:java 节假日判断 编辑:程序博客网 时间:2024/05/17 18:46

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.

思路:哈希

class Solution {public:    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {        vector<int> hash(1000,0);        for(int i = 0; i < nums1.size(); ++i)        {            if(hash[nums1[i]] == 0)                hash[nums1[i]]++;        }        for(int i = 0; i < nums2.size(); ++i)        {            if(hash[nums2[i]] == 1)                hash[nums2[i]]++;        }        vector<int> result;        for(int i = 0; i < hash.size(); ++i)        {            if(hash[i] == 2)               result.push_back(i);        }        return result;    }};
0 0
原创粉丝点击