两数组的交Ⅱ

来源:互联网 发布:淘宝网军用皮鞋女式 编辑:程序博客网 时间:2024/04/29 22:26

题目:两数组的交Ⅱ


问题描述:

计算两个数组的交

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

样例

nums1 = [1, 2, 2, 1], nums2 = [2, 2], 返回 [2, 2].


思路:先把两个数组排序,然后计算出它们的元素个数,再建一个新的vector容器来装重复的元素。利用循环,将nums1和nums2中相等的元素放到vector中,返回vector。


代码:

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
        sort(nums1.begin(), nums1.end());
        sort(nums2.begin(), nums2.end());
        int i=0, j=0;
        int num1 = nums1.size();
        int num2 = nums2.size();
        vector<int> v;
        while(i<num1 && j<num2)
        {
            if(nums1[i] == nums2[j])
            {
               v.push_back(nums1[i]);
               i++;
               j++;
            }
            else if(nums1[i] > nums2[j])
            {
                j++;
            }
            else
            {
                i++;
            }
        }
        return v;
    }
};


感想:有些问题不要太投机取巧,不适合用函数的就不要用。




原创粉丝点击