Intersection of Two Arrays II(350)

8432 단어 LeetCode1LeetCode1

Hash Table - Easy

class Solution:
    def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
        
        # 같은 수 중복도 고려
        answer = []
        common = {}
        dic1 = {}
        dic2 = {}
        
        for i in range(len(nums1)):
            if nums1[i] not in dic1:
                dic1[nums1[i]] = 1
            else:
                dic1[nums1[i]] += 1
        
        for i in range(len(nums2)):
            if nums2[i] not in dic2:
                dic2[nums2[i]] = 1
            else:
                dic2[nums2[i]] += 1
                
        dic2 = list(dic2.items())
        
        
        for i in range(len(dic2)):
            if dic2[i][0] in dic1 and dic1[dic2[i][0]] >= dic2[i][1]:
                for j in range(dic2[i][1]):
                    answer.append(dic2[i][0])
            elif dic2[i][0] in dic1 and dic1[dic2[i][0]] < dic2[i][1]:
                for j in range(dic1[dic2[i][0]]):
                    answer.append(dic2[i][0])
                        
        return answer

좋은 웹페이지 즐겨찾기