Lintcode——两数组的交 II 

1.题目

     计算两个数组的交

  注意事项

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

样例

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

2.思路

     首先对两个数组分别排序;

      然后从头开始遍历比对两个数组(当1数组的i位小于2数组的j位时,可以直接下移比对1数组的i+1位和2数组的j位;2数组j位小于1数组的i位时则2数组下移,比对2数组j+1位和1数组的i位。);

      当比对到相同元素时加入到交数组中。

       因为题目要求每个元素出现次数得和在数组里一样,所以不用像“两数组的交”一样需要特殊处理了。

3.代码

class Solution {
public:
    /**
     * @param nums1 an integer array
     * @param nums2 an integer array
     * @return an integer array
     */
    vector intersection(vector& nums1, vector& nums2) {
        // Write your code here
         vector re;
        int i=0;
        int j=0;
        sort(nums1.begin(),nums1.end());
        sort(nums2.begin(),nums2.end());
        while(inums2[j])
               j++;
             if(nums1[i]==nums2[j])
              {
                re.push_back(nums1[i]);
                i++;  j++;
              }
        }
         return re;
    }
};

4.感想

          本来看题目以为“两数组的交 II ”会比“两数组的交 ”要难,,没想到这道题比 “两数组的交 ”要简单一些。不用其他的处理,直接找到相同元素就可以加到新数组中。。

         如果是先做了另一道题,这道题就显得很简单了。



你可能感兴趣的:(排序)