Leetcode 349. Intersection of Two Arrays
Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique, and you may return the result in any order.
Example 1:
nums1 = [1,2,2,1], nums2 = [2,2][2]Example 2:
nums1 = [4,9,5], nums2 = [9,4,9,8,4][9,4][4, 9] is also accepted.Set Data Structure: Use sets to easily manage and find the intersection of elements.
nums1 and nums2 to sets to eliminate duplicates.set_intersection algorithm to find common elements.nums1 and nums2 to sets.nums1 and m is the size of nums2.#include <vector>
#include <set>
#include <algorithm>
std::vector<int> intersection(std::vector<int>& nums1, std::vector<int>& nums2) {
std::set<int> set1(nums1.begin(), nums1.end());
std::set<int> set2(nums2.begin(), nums2.end());
std::vector<int> result;
std::set_intersection(set1.begin(), set1.end(), set2.begin(), set2.end(), std::back_inserter(result));
return result;
}
nums1 and another set from nums2 to eliminate duplicates and facilitate intersection finding.std::set_intersection from the Standard Library to find the common elements between the two sets.This approach ensures that we efficiently find the unique intersection elements between the two input arrays.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?