소프트웨어에 대한 모든 것

LeetCode 풀이 - 1512. Number of Good Pairs 본문

알고리즘/LeetCode

LeetCode 풀이 - 1512. Number of Good Pairs

앤테바 2021. 10. 21. 01:00
반응형

1512. Number of Good Pairs

문제)

솔루션1)

class Solution:
    def numIdenticalPairs(self, nums: List[int]) -> int:
        # brute-force
        # O(n2)
        count = 0
        for i in range(len(nums)):
            for j in range(1, len(nums)):
                if nums[i] == nums[j] and i < j:
                    count += 1
        return count

솔루션2)

class Solution:
    def numIdenticalPairs(self, nums: List[int]) -> int:        
        count_dict = defaultdict(int)
        count = 0
        for num in nums:
            count += count_dict[num]
            count_dict[num] += 1
        return count

 

반응형
Comments