From a87537f7246a5d5221a540aeb58da3362314821c Mon Sep 17 00:00:00 2001 From: Hiro Funatsuka Date: Tue, 21 Apr 2026 22:32:43 +0900 Subject: [PATCH] Solve intersection of two arrays --- README.md | 2 +- step1.md | 16 ++++++++++++++++ step2.md | 9 +++++++++ step3.md | 9 +++++++++ 4 files changed, 35 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index b9c1787..99807fb 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # LeetCode -## 問題: +## 問題: [349. Intersection of Two Arrays](https://leetcode.com/problems/intersection-of-two-arrays/description/) ## 前提 diff --git a/step1.md b/step1.md index 656f813..37aaac3 100644 --- a/step1.md +++ b/step1.md @@ -1,4 +1,20 @@ # Step 1 +1. nums1から重複を取り除く +2. nums2でループを回し、整数がnums1にあったらその数をresに追加、nums1から除外 + ```python +class Solution: + def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: + res = [] + nums1_without_duplicates = {num for num in nums1} + for num in nums2: + if num in nums1_without_duplicates: + res.append(num) + nums1_without_duplicates.remove(num) + return res + ``` + +時間計算量: O(n) +空間計算量: O(n) diff --git a/step2.md b/step2.md index 6ec3360..d2c7363 100644 --- a/step2.md +++ b/step2.md @@ -1,4 +1,13 @@ # Step 2 ```python +class Solution: + def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: + res = [] + nums1_without_duplicates = set(nums1) + for num in nums2: + if num in nums1_without_duplicates: + res.append(num) + nums1_without_duplicates.remove(num) + return res ``` diff --git a/step3.md b/step3.md index fc9cd1b..2fa271f 100644 --- a/step3.md +++ b/step3.md @@ -1,4 +1,13 @@ # Step 3 ```python +class Solution: + def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: + res = [] + nums1_without_duplicates = set(nums1) + for num in nums2: + if num in nums1_without_duplicates: + res.append(num) + nums1_without_duplicates.remove(num) + return res ```