diff options
| author | 3gg <3gg@shellblade.net> | 2025-02-05 18:36:31 -0800 |
|---|---|---|
| committer | 3gg <3gg@shellblade.net> | 2025-02-05 18:36:31 -0800 |
| commit | 4689e4e80b479be25f7557d05818f5caa723aafa (patch) | |
| tree | 4df25811fe2a9a15b401375178da6537f4b6063f /top-interview-questions/easy/array/06_intersection_of_two_arrays_II.cc | |
Diffstat (limited to 'top-interview-questions/easy/array/06_intersection_of_two_arrays_II.cc')
| -rw-r--r-- | top-interview-questions/easy/array/06_intersection_of_two_arrays_II.cc | 27 |
1 files changed, 27 insertions, 0 deletions
diff --git a/top-interview-questions/easy/array/06_intersection_of_two_arrays_II.cc b/top-interview-questions/easy/array/06_intersection_of_two_arrays_II.cc new file mode 100644 index 0000000..0921be8 --- /dev/null +++ b/top-interview-questions/easy/array/06_intersection_of_two_arrays_II.cc | |||
| @@ -0,0 +1,27 @@ | |||
| 1 | class Solution { | ||
| 2 | public: | ||
| 3 | vector<int> intersect(vector<int>& nums1, vector<int>& nums2) { | ||
| 4 | std::sort(nums1.begin(), nums1.end()); | ||
| 5 | std::sort(nums2.begin(), nums2.end()); | ||
| 6 | |||
| 7 | std::vector<int> result; | ||
| 8 | result.reserve(std::max(nums1.size(), nums2.size())); | ||
| 9 | |||
| 10 | size_t i = 0; | ||
| 11 | size_t j = 0; | ||
| 12 | |||
| 13 | while ((i < nums1.size()) && (j < nums2.size())) { | ||
| 14 | if (nums1[i] == nums2[j]) { | ||
| 15 | result.push_back(nums1[i]); | ||
| 16 | ++i; | ||
| 17 | ++j; | ||
| 18 | } else if (nums1[i] < nums2[j]) { | ||
| 19 | ++i; | ||
| 20 | } else { | ||
| 21 | ++j; | ||
| 22 | } | ||
| 23 | } | ||
| 24 | |||
| 25 | return result; | ||
| 26 | } | ||
| 27 | }; | ||
