Life is endless, you can’t stop answering questions, learn knowledge points from simple questions

2215. Find the difference between two arrays

Easy Difficulty 7 Collection and Sharing Switch to English to receive dynamic feedback

Given two  integer arrays  with  0 subscripts starting from the beginning   , please return a   list  of length  , where:nums1nums22answer

  • answer[0] is   a list of nums1 all distinct integers  in that   are not  present in  .nums2
  • answer[1] is   a list of nums2 all distinct integers  in that   are not  present in  .nums1

Note: The integers in the list can be returned in  any  order.

Example 1:

Input: nums1 = [1,2,3], nums2 = [2,4,6]
 Output: [[1,3],[4,6]]
 Explanation:
 For nums1, nums1[1] = 2 appears in nums2 at subscript 0, however nums1[0] = 1 and nums1[2] = 3 do not appear in nums2. Therefore, answer[0] = [1,3].
For nums2, nums2[0] = 2 appears at index 1 in nums1, but nums2[1] = 4 and nums2[2] = 6 do not appear in nums2. Therefore, answer[1] = [4,6].

Example 2:

Input: nums1 = [1,2,3,3], nums2 = [1,1,2,2]
 Output: [[3],[]]
 Explanation:
 For nums1, nums1[2] and nums1[3] are not Appears in nums2. Since nums1[2] == nums1[3], the two values ​​only need to appear once in answer[0], so answer[0] = [3].
Every integer in nums2 occurs in nums1, therefore, answer[1] = [].

hint:

  • 1 <= nums1.length, nums2.length <= 1000
  • -1000 <= nums1[i], nums2[i] <= 1000

Number of passes: 10,795 Number of submissions: 16,126

Solution: The question has said so much, but it is actually the difference between the two sets. This has been implemented in C++ and can be called directly.

class Solution {
public:
    vector<vector<int>> findDifference(vector<int>& nums1, vector<int>& nums2) {
         set<int> s1(nums1.begin(), nums1.end());
        set<int> s2(nums2.begin(), nums2.end());
        vector<int> v1, v2;
        set_difference(s1.begin(), s1.end(), s2.begin(), s2.end(), back_inserter(v1));
        set_difference(s2.begin(), s2.end(), s1.begin(), s1.end(), back_inserter(v2));
        return {v1, v2};
    }
};

If you encounter other set operations, please add more.

Guess you like

Origin blog.csdn.net/weixin_41579872/article/details/126054379