Intersection of Two Arrays II

Given two arrays, write a function to compute their intersection.

Example:
Given nums1 = [1, 2, 2, 1]nums2 = [2, 2], return [2, 2].

Note:

  • Each element in the result should appear as many times as it shows in both arrays.
  • The result can be in any order.
  • 思路:先将两个数组排序,这样被比较数组遍历一次即可。nums1中的元素,从前到后在nums2中查找
  • 分三种情况:
  • 1. 如果nums2的元素大于nums1的当前元素,说明nums2中不存在此元素。
  • 2. 如果nums2的元素等于nums1的当前元素,那么该元素为两个数组的交集,两个指针都前进。
  • 3. 如果nums2的元素小于nums的当前元素,nums2的指针继续向后找。
  • 具体实现如下:
  • class Solution {
    public:
        vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
            vector<int> result;
            sort(nums1.begin(),nums1.end());
            sort(nums2.begin(),nums2.end());
            int ind1=0;
            int ind2 = 0;
            while(ind1<nums1.size() && ind2<nums2.size()){
                if(nums1[ind1]<nums2[ind2]){
                    ind1++;
                }else if(nums1[ind1]==nums2[ind2]){
                    result.push_back(nums1[ind1]);
                    ind1++;
                    ind2++;
                }else{
                    ind2++;
                }
                
            }
            
            return result;
            
        }
    };

     

posted @ 2016-06-29 14:22  mokayy  阅读(136)  评论(0编辑  收藏  举报