Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions solutions/0301-0400/0350-intersection-of-two-arrays-ii/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# 350. Intersection of Two Arrays II

[LeetCode problem 350](https://leetcode.com/problems/intersection-of-two-arrays-ii/)

- **Difficulty**: Easy
- **Tags**: array, hash-table, two-pointers, sorting

## Description

Given two integer arrays `nums1` and `nums2`, return an array of their
intersection, where each element in the result appears as many times as it
shows in both arrays (order doesn't matter).
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
#include "solution.hpp"

#include <unordered_map>

namespace leetcode::p0350 {

std::vector<int> solve(const std::vector<int>& nums1, const std::vector<int>& nums2) {
std::unordered_map<int, int> counts;
for (int value : nums1) {
++counts[value];
}

std::vector<int> result;
for (int value : nums2) {
auto it = counts.find(value);
if (it != counts.end() && it->second > 0) {
result.push_back(value);
--it->second;
}
}

return result;
}

} // namespace leetcode::p0350
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
#pragma once

#include <vector>

namespace leetcode::p0350 {

// optimized: O(n + m) time, O(min(n, m)) space — count occurrences of the
// smaller array, then consume counts while scanning the other.
std::vector<int> solve(const std::vector<int>& nums1, const std::vector<int>& nums2);

} // namespace leetcode::p0350
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
#include <catch2/catch_test_macros.hpp>

#include "solution.hpp"

TEST_CASE("Problem 350", "[p0350]") {
CHECK(leetcode::p0350::solve({1, 2, 2, 1}, {2, 2}) == std::vector<int>{2, 2});
CHECK(leetcode::p0350::solve({4, 9, 5}, {9, 4, 9, 8, 4}) == std::vector<int>{9, 4});
}
19 changes: 0 additions & 19 deletions swift/350.swift

This file was deleted.

Loading