본문 바로가기

Python/코딩테스트

[백준] 1822. 차집합

백준 1822. 차집합

 

1822번: 차집합

첫째 줄에는 집합 A의 원소의 개수 n(A)와 집합 B의 원소의 개수 n(B)가 빈 칸을 사이에 두고 주어진다. (1 ≤ n(A), n(B) ≤ 500,000)이 주어진다. 둘째 줄에는 집합 A의 원소가, 셋째 줄에는 집합 B의 원소

www.acmicpc.net

 

 난이도 : 실버 4

 문제 풀이 : 이분탐색, set 함수 사용 (차집합)

 

< 이분탐색 사용 > 

import math
import sys
input = sys.stdin.readline

n, m = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
res = []

b.sort()
for x in a:
    tmp = x
    s, e = 0, m-1
    while s <= e:
        mid = (s+e)//2

        if b[mid] == x:
            tmp = 0
            break

        elif b[mid] < x:
            s = mid+1

        else:
            e = mid-1

    if tmp != 0:
        res.append(tmp)
        
print(len(res))
if len(res) > 0:
    print(*sorted(res))

 

< set 사용 >

import sys
input = sys.stdin.readline

n, m = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))

res = list(set(a)-set(b))
res.sort()

print(len(res))
if len(res) != 0:
    print(' '.join(map(str, res)))

 


내장함수인 set을 사용하는 것이 훨씬! 시간이 빨랐다. 아무래도 set의 특성때문인 것 같다. 그치만 공간 메모리는 이분탐색이 더 작은 것을 알 수 있었다. set 함수도 좀 더 공부해야겠다.

'Python > 코딩테스트' 카테고리의 다른 글

[백준] 10815. 숫자 카드  (1) 2023.10.09
[백준] 10816. 숫자 카드 2  (0) 2023.10.09
[백준] 1920. 수찾기  (0) 2023.10.09
[백준] 2330번 : 수 고르기  (1) 2023.09.23
[백준] 구현 기초 - 별 찍기 1~7  (0) 2023.09.21