본문 바로가기

Algorithm/자료구조

(Python3) - LeetCode (Easy) : 3731. Find Missing Elements

반응형

https://leetcode.com/problems/find-missing-elements

 

Find Missing Elements - LeetCode

Can you solve this real interview question? Find Missing Elements - You are given an integer array nums consisting of unique integers. Originally, nums contained every integer within a certain range. However, some integers might have gone missing from the

leetcode.com

set 을 사용해본 문제였습니다. 값만 저장하는 자료구조로 저장 삽입 삭제가 O(1)입니다

📕 풀이방법

📔 입력 및 초기화

📑 nums_set을 선언해 list인 nums를 set으로 변환 후 저장합니다.

📑 정답변수 list ans를 선언합니다.

📔 풀이과정

📑 nums의 최솟값 ~ 최댓값 - 1 만큼 순회하며 다음 조건을 검사합니다
nums_set에 현재 확인하는 정수값 num이 없다면 비어있는 상황이므로 ans에 num을 append해줍니다

📑 시간 복잡도

O(n): 배열의 원소들을 한 번씩 순회하기 때문입니다.

📑 공간 복잡도

O(n): 배열의 원소만큼 set이 가지기 때문입니다.

📔 정답 출력 | 반환

ans를 반환합니다.


📕 Code

📔 Python3

class Solution:
    def findMissingElements(self, nums: List[int]) -> List[int]:
        nums_set = set(nums)
        ans = []
        for num in range(min(nums), max(nums)):
            if num not in nums_set:
                ans.append(num)
        return ans

 


*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.