两数组的交 II

来源:互联网 发布:单片机软件工程师招聘 编辑:程序博客网 时间:2024/04/29 23:32

1、问题描述

     计算两个数组的交

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

2、实现思路

     将两个数组排序,nums1的每个元素依次和nums2中元素比较是否相等,因为排过序,若nums1中的元素比nums2中某位置的值小,一定比nums2此元素之后所有的小,不需要比较,比较过了的nums2的元素不需要再比较了。

3、代码

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> c;
        int a=nums1.size();
        int k=0;
        int i,j,n;
        sort(nums1.begin(),nums1.end());
        sort(nums2.begin(),nums2.end());
        for(i=0;i<a;i++)
           {for(j=k;j<nums2.size();j++)
             {if(nums1[i]<nums2[j]) break;
              if(nums1[i]==nums2[j])
               { c.push_back(nums1[i]);
                 k=j+1;
                 break;}
             }
           }
        return c;
    }
};

4、感想

     和两数组的交的区别是如果两数组都有两个相同的元素,重复的不需要删除。continue是跳出此次迭代,继续进项下一层循环,break是跳出for循环。

原创粉丝点击