码迷,mamicode.com
首页 > 其他好文 > 详细

350. Intersection of Two Arrays II(LeetCode)

时间:2017-05-08 23:27:49      阅读:237      评论:0      收藏:0      [点我收藏+]

标签:color   put   can   mem   already   nts   i++   log   store   

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 nums2‘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?
       1 class Solution {
       2 public:
       3     vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
       4         sort(nums1.begin(), nums1.end());
       5         sort(nums2.begin(), nums2.end());
       6         int len1 = nums1.size();
       7         int len2 = nums2.size();
       8         
       9         int i = 0;
      10         int j = 0;
      11         vector<int> vet;
      12         while (i < len1&&j < len2)
      13         {
      14             if (nums1[i] == nums2[j])
      15             {
      16                 vet.push_back(nums1[i]);
      17                 i++;
      18                 j++;
      19             
      20             }
      21             else
      22             {
      23                 if (nums1[i] < nums2[j])
      24                 {
      25                     i++;
      26                 }
      27                 else
      28                 {
      29                     j++;
      30                 }
      31             }
      32         }
      33         return vet;
      34     }
      35 };

       

350. Intersection of Two Arrays II(LeetCode)

标签:color   put   can   mem   already   nts   i++   log   store   

原文地址:http://www.cnblogs.com/wujufengyun/p/6828199.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!