개발/Leetcode

Leetcode 137. Single Number II

지산동고라니 2023. 7. 4. 09:11

https://leetcode.com/problems/single-number-ii/description/

 

Single Number II - LeetCode

Can you solve this real interview question? Single Number II - Given an integer array nums where every element appears three times except for one, which appears exactly once. Find the single element and return it. You must implement a solution with a lin

leetcode.com

문제

정수 배열인 nums가 주어진다. 이 배열은 한 원소만 정확히 한번만 등장하고 나머지 원소는 3번씩 등장한다. 이때 한번만 등장하는 원소를 반환하여라

 

이 문제는 O(n)의 복잡도를 지닌 코드만 통과할 수 있습니다.

 

코드

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        m = {}
        for n in nums:
            if n not in m:
                m[n] = 0
            m[n] +=1

        return list(filter(lambda x: m[x] == 1, m))[0]