diff --git a/300-400q/349.py b/300-400q/349.py new file mode 100644 index 0000000..3a8b8d9 --- /dev/null +++ b/300-400q/349.py @@ -0,0 +1,37 @@ +''' +Given two arrays, write a function to compute their intersection. + +Examples +-------- +Input: nums1 = [1,2,2,1], nums2 = [2,2] +Output: [2] + +Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] +Output: [9,4] +''' + +class Solution: + def intersection(self, arrA: List[int], arrB: List[int]) -> List[int]: + + arrA.sort() + arrB.sort() + + intersection = [] + + aIndex = 0 + bIndex = 0 + recentOverlap = None + + while aIndex < len(arrA) and bIndex < len(arrB): + if arrA[aIndex] > arrB[bIndex]: + bIndex += 1 + elif arrA[aIndex] == arrB[bIndex]: + if arrB[bIndex] != recentOverlap: # skip duplicate overlapping elements + recentOverlap = arrB[bIndex] + intersection.append(recentOverlap) + bIndex += 1 # you could increment aIndex instead + else: + # arrA[aIndex] < arrB[bIndex] + aIndex += 1 + + return intersection \ No newline at end of file diff --git a/README.md b/README.md index 9f03b51..c439f99 100644 --- a/README.md +++ b/README.md @@ -143,6 +143,7 @@ Python solution of problems from [LeetCode](https://leetcode.com/). |378|[Kth Smallest Element in a Sorted Matrix](https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix) | [Python](./300-400q/378.py)|Medium| |361|[Bomb Enemy](https://leetcode.com/problems/bomb-enemy)|[Python](./300-400q/361.py)|Medium| |350|[Intersection of Two Arrays II](https://leetcode.com/problems/intersection-of-two-arrays-ii/) | [Python](./300-400q/350.py)|Easy| +|349|[Intersection of Two Arrays](https://leetcode.com/problems/intersection-of-two-arrays/) | [Python](./300-400q/349.py) | Easy | |347|[Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/) | [Python](./300-400q/347.py)|Medium| |346|[Moving Average from Data Stream](https://leetcode.com/problems/moving-average-from-data-stream)|[Python](./300-400q/346.py)|Easy| |340|[Longest Substring with At Most K Distinct Characters](https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters)|[Python](./300-400q/340.py)|Hard|