🖋
LeetCode 349. Intersection of Two Arrays (Python3)
はじめに
LeetCode 「349. Intersection of Two Arrays」の問題を Python3 で解きました。
問題
問題文
Given two integer arrays nums1
and nums2
, return an array of their intersection. Each element in the result must be unique and you may return the result in any order.
和訳
2つの整数配列 nums1
と nums2
が与えられ、それらの交差部分の配列を返します。結果の各要素は一意である必要があり、任意の順序で結果を返すことができます。
例
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]
Explanation: [4,9] is also accepted.
制約
- 1 <= nums1.length, nums2.length <= 1000
- 0 <= nums1[i], nums2[i] <= 1000
解答1
2つの配列の現れる要素を返す問題です。
重複を排除してユニークにする必要があります。
setを使うと簡潔に解答することが可能です。
セット(集合)はリストと同様に複数の要素から構成されるデータで、要素の重複がありません。
配列をsetに変換して、積集合を使うことで求めることができます。
コード
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
return list(set(nums1) & set(nums2))
計算量
- 時間的計算量:O(n + m)
- nums1・nums2を集合に変換し、積集合を取る処理
- 空間的計算量:O(n + m)
- 集合の作成に必要なメモリ
Discussion