본문 바로가기
Python/PS in Python

LeetCode 448. Find All Numbers Disappeared in an Array

by Air’s Big Data 2020. 8. 18.

LeetCode 448. Find All Numbers Disappeared in an Array - Python

Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.

Find all the elements of [1, n] inclusive that do not appear in this array.

Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.

 

Example:

Input:
[4,3,2,7,8,2,3,1]

Output:
[5,6]

 

Solution 1:

class Solution(object):
    def findDisappearedNumbers(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        return list(set(range(1, len(nums)+1)) - set(nums))

 

Solution 2:

class Solution:
    def findDisappearedNumbers(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        for n in nums:
            i = abs(n) - 1
            nums[i] = -abs(nums[i])
        return [i+1 for i, v in enumerate(nums) if v > 0]

 

Solution 3:

class Solution: 
    def findDisappearedNumbers(self, nums: List[int]) -> List[int]: 
        if len(nums) < 0: 
            answer = [] 
        else: 
            max_num = len(nums)
            answer = list(set(range(1,max_num + 1)) - set(nums)) 
        return answer

 

 

(참고 자료)

솔루션 출처 :

https://nifannn.github.io/2017/10/28/Algorithm-Notes-Leetcode-448-Find-All-Numbers-Disappeared-in-an-Array/

https://somjang.tistory.com/entry/leetCode-448-Find-All-Numbers-Disappeared-in-an-Array-Python

 

집합(set) 자료형 - 차집합 : www.notion.so/set-2373e7be9750401ab8ec2de707adfb39

내장 함수 - enumerate() : www.notion.so/ecbd6e96aea84e67aab7b5afd47307c2

내장 함수 - abs() : www.notion.so/ecbd6e96aea84e67aab7b5afd47307c2

댓글