[LeetCode][Python3] 350. Intersection of Two Arrays II
                2018. 11. 5. 22:46 |
                
                    프로그래밍/LeetCode
                
            
            
            
        Problem :
https://leetcode.com/problems/intersection-of-two-arrays-ii/
My Solution :
class Solution:
    def intersect(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        nums1.sort()
        nums2.sort()
        ans = []
        i = j = 0
        while i < len(nums1) and j < len(nums2):
            if nums1[i] == nums2[j]:
                ans.append(nums1[i])
                i += 1
                j += 1
            elif nums1[i] > nums2[j]:
                j += 1
            else:
                i += 1
        return ans
Comment :
위 풀이는 정렬을 먼저 해놓고 포인터를 증가시키며 비교하는 것이다. 아래 풀이는 Dictionary를 이용한 것.
My Solution2 :
class Solution:
    def intersect(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        ans = []
        counter = dict()
        for n in nums1:
            counter[n] = counter.get(n, 0) + 1
        for n in nums2:
            if counter.get(n, 0) > 0:
                ans.append(n)
                counter[n] -= 1
        return ans
'프로그래밍 > LeetCode' 카테고리의 다른 글
| [LeetCode][Python3] 17. Letter Combinations of a Phone Number (0) | 2018.11.09 | 
|---|---|
| [LeetCode][Python3] 11. Container With Most Water (0) | 2018.11.07 | 
| [LeetCode][Python3] 108. Convert Sorted Array to Binary Search Tree (0) | 2018.11.06 | 
| [LeetCode][Python3] 387. First Unique Character in a String (0) | 2018.11.05 | 
| [LeetCode][Python3] 344. Reverse String (0) | 2018.11.05 | 
| [LeetCode][Python3] 268. Missing Number (0) | 2018.11.04 | 
| [LeetCode][Python3] 242. Valid Anagram (0) | 2018.11.04 | 
| [LeetCode][Python3] 237. Delete Node in a Linked List (0) | 2018.11.04 | 
최근에 달린 댓글 최근에 달린 댓글