两数组的交 II-LintCode

来源:互联网 发布:java 高性能 高并发 编辑:程序博客网 时间:2024/05/21 17:26

计算两个数组的交

注意事项:
每个元素出现次数得和在数组里一样
答案可以以任意顺序给出

样例:
nums1 = [1, 2, 2, 1], nums2 = [2, 2], 返回 [2, 2].

挑战 :
What if the given array is already sorted? How would you optimize your algorithm?
What if nums1’s size is small compared to num2’s size? Which algorithm is better?
What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?

#ifndef C548_H#define C548_H#include<vector>#include<iostream>#include<map>using namespace std;class Solution {public:    /*    * @param nums1: an integer array    * @param nums2: an integer array    * @return: an integer array    */    vector<int> intersection(vector<int> nums1, vector<int> nums2) {        // write your code here        vector<int> res;        if (nums1.empty() || nums2.empty())            return res;        map<int,int> m1,m2;        for (auto c : nums1)            m1[c]++;        for (auto t : nums2)            m2[t]++;        for (auto it = m2.begin(); it != m2.end(); ++it)        {            if (m1.find(it->first) != m1.end())            {                int num = minVal(it->second, m1[it->first]);                while (num>0)                {                    res.push_back(it->first);                    num--;                }            }        }        return res;    }    int minVal(int a, int b)    {        return a < b ? a : b;    }}; #endif
原创粉丝点击