找两个数组的重合数字系列

【leetcode】349. Intersection of Two Arrays

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.

Subscribe to see which companies asked this question

分析:

这道题目给出的结果是重复元素只返回一个的,有两种解决方法,一种是可以先分别对这两个数组进行排序,然后开始进行遍历,如果遇到相等的,则放入结果集中,如果第一个数组的元素小于第二个,则第一个的指针往后走一个,反之则第二个数组的指针往后走。那么遇到重复的元素怎么办呢,其实有两种处理方法,一种是先全部统计,不管它,最后再在结果数组中去重;另一种是在遍历的时候直接对重复的元素进行跳过操作。这种方法的两类处理方式的代码分别如下:

 1 class Solution {
 2 public:
 3     vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
 4          vector<int>res;
 5             if(nums1.empty()||nums2.empty())
 6                 return res;
 7          sort(nums1.begin(),nums1.end());
 8          sort(nums2.begin(),nums2.end());
 9          for(int i=0;i<nums1.size();i++)
10             for(int j=0;j<nums2.size();j++)
11             {
12                 if(nums1[i]==nums2[j])
13                     res.push_back(nums1[i]);
14             }
15         vector<int>::iterator pos;
16         pos=unique(res.begin(),res.end());
17         res.erase(pos,res.end());
18         return res;
19     }
20 };

这里有一个问题,为什么在使用unique函数之后还要用erase从pos的位置开始一直擦除到res的结尾处呢?

这是因为:

类属性算法unique的作用是从输入序列中“删除”所有相邻的重复元素

该算法删除相邻的重复元素,然后重新排列输入范围内的元素,并且返回一个迭代器(容器的长度没变,只是元素顺序改变了),表示无重复的值范围得结束。

复制代码
 1 // sort words alphabetically so we can find the duplicates 
 2 sort(words.begin(), words.end()); 
 3      /* eliminate duplicate words: 
 4       * unique reorders words so that each word appears once in the 
 5       *    front portion of words and returns an iterator one past the 
 6 unique range; 
 7       * erase uses a vector operation to remove the nonunique elements 
 8       */ 
 9  vector<string>::iterator end_unique =  unique(words.begin(), words.end()); 
10  words.erase(end_unique, words.end());
复制代码
在STL中unique函数是一个去重函数, unique的功能是去除相邻的重复元素(只保留一个),其实它并不真正把重复的元素删除,是把重复的元素移到后面去了,然后依然保存到了原数组中,然后 返回去重后最后一个元素的地址,因为unique去除的是相邻的重复元素,所以一般用之前都会要排一下序。

若调用sort后,vector的对象的元素按次序排列如下:

sort  jumps  over quick  red  red  slow  the  the turtle

则调用unique后,vector中存储的内容是:

 

 

 

 

 

 

注意,words的大小并没有改变,依然保存着10个元素;只是这些元素的顺序改变了。调用unique“删除”了相邻的重复值。给“删除”加上引号是因为unique实际上并没有删除任何元素,而是将无重复的元素复制到序列的前段,从而覆盖相邻的重复元素。unique返回的迭代器指向超出无重复的元素范围末端的下一个位置。

注意:算法不直接修改容器的大小。如果需要添加或删除元素,则必须使用容器操作。

posted @ 2016-10-27 16:36  SarahLiu77  阅读(731)  评论(0编辑  收藏  举报