백준 알고리즘 - 1920. 수 찾기
2024. 3. 6. 18:51ㆍ코딩 테스트/백준
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
전체 코드
bisect 사용
# Code
###################### bisect 사용 ############################
import bisect
def solution(nums, find_nums):
def binary_search(nums_arr, target):
index = bisect.bisect_left(nums_arr, target)
if index < len(nums_arr) and nums_arr[index] == target:
return True
return False
nums.sort()
result = [1 if binary_search(nums, find_num) else 0 for find_num in find_nums]
return result
# --- submit ---
num_count = input()
nums = list(map(int, input().split()))
find_num_count = input()
find_nums = list(map(int, input().split()))
datas = solution(nums, find_nums)
for d in datas:
print(d)
반복문 사용
###################### 반복문 구현 ##############################
def solution(src_nums, target_nums):
def binary_search(nums_arr, target):
left, right = 0, len(nums_arr) - 1
while left <= right:
mid = (right + left) // 2
mid_val = nums_arr[mid]
if mid_val > target:
right = mid - 1
elif mid_val < target:
left = mid + 1
else:
return True
return False
src_nums.sort()
result = [1 if binary_search(src_nums, find_num) else 0 for find_num in target_nums]
return result
# --- submit ---
num_count = input()
nums = list(map(int, input().split()))
find_num_count = input()
find_nums = list(map(int, input().split()))
datas = solution(nums, find_nums)
for d in datas:
print(d)
'코딩 테스트 > 백준' 카테고리의 다른 글
백준 알고리즘 - 2805. 나무 자르기 (1) | 2024.03.06 |
---|---|
백준 알고리즘 - 1654. 랜선 자르기 (0) | 2024.03.06 |
백준 알고리즘 - 2566. 최댓값 (0) | 2024.03.06 |
백준 알고리즘 - 2563. 색종이 (0) | 2024.03.06 |
백준 알고리즘 1931. 회의실 배정 (0) | 2024.03.05 |