350. Intersection of Two Arrays II

Total Accepted: 3237  Total Submissions: 7617  Difficulty: Easy

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.

Follow up:

  • What if the given array is already sorted? How would you optimize your algorithm?
  • What if nums1's size is small compared to num2's size? Which algorithm is better?
  • What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?

Subscribe to see which companies asked this question

Hide Tags
  Binary Search Hash Table Two Pointers Sort
Hide Similar Problems
  (E) Intersection of Two Arrays

分析:

先让数组有序,再双指针遍历即可,有相同元素就获取结果,然后判断下一对

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 i=0;
        int j=0;
        while(i < nums1.size() && j < nums2.size())//双指针遍历
        {
            if(nums1[i] < nums2[j])
                i++;
            else if(nums1[i] > nums2[j])//移动
                j++;
            else//相等,获取结果
             {
                result.push_back(nums1[i]);
                i++;j++;
             }
        }
        return result;  
    }
};



注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!

原文地址:http://blog.csdn.net/ebowtang/article/details/51488374

原作者博客:http://blog.csdn.net/ebowtang

本博客LeetCode题解索引:http://blog.csdn.net/ebowtang/article/details/50668895

你可能感兴趣的:(LeetCode,C++,技术,面试,遍历)