-
리트코드 - 2215. Find the Difference of Two Arrays코딩테스트 2023. 12. 28. 02:25728x90
https://leetcode.com/problems/find-the-difference-of-two-arrays/description/
Find the Difference of Two Arrays - LeetCode
Can you solve this real interview question? Find the Difference of Two Arrays - Given two 0-indexed integer arrays nums1 and nums2, return a list answer of size 2 where: * answer[0] is a list of all distinct integers in nums1 which are not present in nums2
leetcode.com
두 개의 0 인덱스 정수 배열 nums1과 nums2가 주어졌을 때, 여기서 크기가 2인 리스트을 반환하도록 한다.
리스트의 각 요소는 주어진 정수 배열의 모든 고유 정수들로 구성되어야 한다.
class Solution: def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]: res = [] list1, list2 = set(nums1), set(nums2) # O(n + m) res.append(list(list1 - list2)) # O(n) res.append(list(list2 - list1)) # O(m) return resset1의 각 요소를 순회하며 set2에 존재하지 않는 요소들만을 선택하여 집합을 구성한다. 따라서 이 연산의 시간 복잡도는 set1의 크기에 비례하는 O(N)이 된다.
그 이유는 set 함수는 내부적으로 해시 테이블을 사용하여 데이터를 저장하기 때문에 in 연산을 평균 O(1)의 시간 복잡도로 수행할 수 있기 때문이다.
728x90'코딩테스트' 카테고리의 다른 글
리트코드 - 238. Product of Array Except Self (2) 2024.01.03 리트코드 - 724. Find Pivot Index (0) 2023.12.31 리트코드 - 746. Min Cost Climbing Stairs (1) 2023.12.27 리트코드 - 392. Is Subsequence (1) 2023.12.25 리트코드 - 643. Maximum Average Subarray I (1) 2023.12.23