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

350. Intersection of Two Arrays II

时间:2020-04-02 01:22:47      阅读:64      评论:0      收藏:0      [点我收藏+]

标签:unique   vector   lang   tput   time   inter   array   turn   size   

Problem:

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

Example 1:

Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2]

Example 2:

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [9,4]

Note:

  • Each element in the result must be unique.
  • The result can be in any order.

思路

Solution (C++):

vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
    if (nums1.empty() || nums2.empty())  return vector<int>{};
    int m = nums1.size(), n = nums2.size(), inter = 0;
    vector<int> res;
    if (m <= n) {
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n-inter; ++j) {
                if (nums1[i] == nums2[j])  { 
                    res.push_back(nums1[i]); 
                    swap(nums2[j], nums2[n-1-inter]);
                    inter++;
                    break;
                }
            }
        }
    } else {
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < m-inter; ++j) {
                if (nums2[i] == nums1[j])  { 
                    res.push_back(nums2[i]); 
                    swap(nums1[j], nums1[m-1-inter]);
                    inter++;
                    break;
                }
            }
        }
    }
    return res;
}

性能

Runtime: 16 ms??Memory Usage: 6.6 MB

思路

Solution (C++):


性能

Runtime: ms??Memory Usage: MB

350. Intersection of Two Arrays II

标签:unique   vector   lang   tput   time   inter   array   turn   size   

原文地址:https://www.cnblogs.com/dysjtu1995/p/12617007.html

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