Skip to content

Latest commit

 

History

History
36 lines (23 loc) · 1.48 KB

File metadata and controls

36 lines (23 loc) · 1.48 KB

⌛️ 349. Intersection of Two Arrays

  • Date : 2021.09.12(일)
  • Time : 15분

Problem

  • 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.

Constraints

  • 1 <= nums1.length, nums2.length <= 1000
  • 0 <= nums1[i], nums2[i] <= 1000

Example

  • Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
  • Output: [9,4]
  • Explanation: [4,9] is also accepted.



풀이

    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
        if len(nums1) > len(nums2) :
            nums1, nums2 = nums2, nums1
            
        answer = list(filter(lambda x: x in nums2, nums1))
        return list(dict.fromkeys(answer))
        

: 이번 문제는 두 배열의 겹치는 요소를 반환하는 문제. 문제 자체는 어렵지 않았다. 속도를 높혀주기 위해 처음에 nums1, nums2의 길이를 반환해서 길이가 짧은 것을 nums1으로 지정하였다. 그 후 filter 함수를 이용해 nums1 배열의 요소 중 nums2 안에 존재한다면 중복이기 때문에 필터링 해줬다. 그리고 이제 요소 중 중복된 것을 거르기 위해 계산을 해줘야한다. 중복을 거르는 방법에는 3가지가 있다. 첫번째는 set을 사용하는 방법, 두번재는 딕셔너리를 사용하는 방법. 세번째가 for문을 사용하는 방법이다. 나는 여기서는 딕셔너리를 이용했다.