📌 탐색 알고리즘
- 이진 탐색
- 순차 탐색
- 코딩 테스트 연습문제 풀이 ✔
실전 코딩 테스트 - 탐색 알고리즘
[백준 1920번]
https://www.acmicpc.net/problem/1920
1920번: 수 찾기
첫째 줄에 자연수 N(1 ≤ N ≤ 100,000)이 주어진다. 다음 줄에는 N개의 정수 A[1], A[2], …, A[N]이 주어진다. 다음 줄에는 M(1 ≤ M ≤ 100,000)이 주어진다. 다음 줄에는 M개의 수들이 주어지는데, 이 수들
www.acmicpc.net
- 시간복잡도 O(n^2)
n = 5
n_list = [4, 1, 5, 2, 3]
m = 5
m_list = [1, 3, 7, 9, 5]
for item in m_list:
if item in n_list:
print(1)
else:
print(0)
- 시간복잡도 O(logn) - 이진 탐색
n = 5
n_list = [4, 1, 5, 2, 3]
m = 5
m_list = [1, 3, 7, 9, 5]
n_list.sort()
def binary_search(value, start, end):
if start > end:
return False
median = (start + end) // 2
if n_list[median] > value:
return binary_search(value, start, median - 1)
elif n_list[median] < value:
return binary_search(value, median + 1, end)
else:
return True
for item in m_list:
if binary_search(item, 0, n - 1):
print(1)
else:
print(0)
n = int(input())
n_list = list(map(int, input().split()))
m = int(input())
m_list = list(map(int, input().split()))
n_list.sort()
def binary_search(value, start, end):
if start > end:
return False
median = (start + end) // 2
if n_list[median] > value:
return binary_search(value, start, median - 1)
elif n_list[median] < value:
return binary_search(value, median + 1, end)
else:
return True
for item in m_list:
if binary_search(item, 0, n - 1):
print(1)
else:
print(0)
'~2023.02 > 알고리즘' 카테고리의 다른 글
[기본 정렬 알고리즘 #1] 버블 정렬 (0) | 2022.02.28 |
---|---|
최단 경로 알고리즘 (0) | 2022.02.28 |
[탐색 알고리즘 #2] 순차 탐색(Sequential Search) (0) | 2022.02.25 |
[탐색 알고리즘 #1] 이진 탐색(Binary Search) (0) | 2022.02.25 |
동적 계획법과 분할 정복 (0) | 2022.02.23 |