문제 링크 : https://leetcode.com/problems/intersection-of-two-arrays-ii/
앞서 풀어봤던 문제에 이어서 nums1과 nums2에서 겹치는 숫자를 리턴하는 문제이다.
이전 문제와 다른점은 중복된 숫자도 다 출력해야 한다는 점이다.
(ex. [1,2,2,5], [2,2,3] 이 있을 때, 2가 아닌 2,2가 출력되어야 한다)
그레서 이전 문제에서 짰던 코드에서 not in ans 조건을 지우고 만들었다. 1차 시도
class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
ans = []
for i in nums1:
if i in nums2:
ans.append(i)
return ans
실패
실패한 테.케
Input
[1,2,2,1][2]
Output
[2,2]
Expected
[2]
...
두 배열 중 하나의 배열의 개수가 한 개이고 나머지 하나의 배열에 중복된 숫자가 두 개 있는 경우.. 중복된 숫자 두개를 모두 출력해야 하는데 위의 코드로 실행할 경우 한 개밖에 안나옴..
하..
그래서
위의 경우들을 대비해서 각각의 조건들을 만들어 2차 시도를 해보았다
class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
ans = []
if len(nums1)<=len(nums2):
for i in nums1:
if i in nums2:
ans.append(i)
elif len(nums2)<len(nums1):
for j in nums2:
if j in nums1:
ans.append(j)
return ans
실패...
실패 테.케:
Input
[3,1,2][1,1]
Output
[1,1]
Expected
[1]
...
Discussion을 찾아보다가 counter를 이용한 방법을 알았다.
class Solution(object):
def intersect(self, nums1, nums2):
c = collections.Counter(nums1)
res = []
for i in nums2:
if c[num] > 0:
res.append(i),
c[num] -= 1
return res
Ex. nums1 = [1,2,2,1] , nums2=[2,1,5]
counter를 이용하여 nums1에 배열들 개수..?를 센다
ex. c = {1:2, 2:2}
그다음에 nums2의 배열중에서 만약 c[n]이 0보다 크다면 nums2의 배열이 nums1에 있다는것이므로 append해주고 중복 방지를 위해서 cnt개수에서 빼준다