zoukankan      html  css  js  c++  java
  • 350. Intersection of Two Arrays II(LeetCode)

    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 };
  • 相关阅读:
    二进制显示整数
    测试intel 8.0
    实用的免费网络空间
    tcp/ip入门(转)
    桶排序
    在talking bar的留言(够无聊)
    重装系统手记
    几个宏
    组合算法<转>
    记深圳慧通面试
  • 原文地址:https://www.cnblogs.com/wujufengyun/p/6828199.html
Copyright © 2011-2022 走看看