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://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
'Python > PS in Python' 카테고리의 다른 글
LeetCode 121. Best Time to Buy and Sell Stock - Python (0) | 2020.08.24 |
---|---|
LeetCode 21. Merge Two Sorted Lists - Python (0) | 2020.08.21 |
LeetCode 283. Move Zeroes - Python (0) | 2020.08.16 |
LeetCode 169. Majority Element - Python (0) | 2020.08.13 |
LeetCode 226. Invert Binary Tree - Python (0) | 2020.08.09 |
댓글