From 9ebf9885c31b12d2f067704697742f88523a5fb8 Mon Sep 17 00:00:00 2001 From: bumpsoo Date: Tue, 2 Jul 2024 21:40:26 +0900 Subject: [PATCH] https://leetcode.com/problems/intersection-of-two-arrays-ii --- easy/intersection_of_two_arrays2.py | 31 +++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 easy/intersection_of_two_arrays2.py diff --git a/easy/intersection_of_two_arrays2.py b/easy/intersection_of_two_arrays2.py new file mode 100644 index 0000000..36c2f73 --- /dev/null +++ b/easy/intersection_of_two_arrays2.py @@ -0,0 +1,31 @@ +# https://leetcode.com/problems/intersection-of-two-arrays-ii +from typing import Dict, List + + +class Solution: + def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]: + s1: Dict[int, int] = {} + s2: Dict[int, int] = {} + ret: List[int] = [] + for v in nums1: + if s1.get(v) == None: + s1[v] = 1 + else: + s1[v] += 1 + for v in nums2: + if s2.get(v) == None: + s2[v] = 1 + else: + s2[v] += 1 + f = len(s1) > len(s2) + loop: Dict[int, int] = s2 if f else s1 + another = s1 if f else s2 + for key in loop.keys(): + if another.get(key) == None: + continue + while loop[key] > 0 and another[key] > 0: + loop[key] -= 1 + another[key] -= 1 + ret.append(key) + return ret +