나의 풀이
1.
n, x = map(int, input().split())
num = list(map(int, input().split()))
def search_start(arr, target, start, end):
if start > end:
return -1
mid = (start + end) // 2
if (mid == 0 or arr[mid - 1] < target) and arr[mid] == target:
return mid
elif arr[mid] >= target:
return search_start(arr, target, start, mid - 1)
else:
return search_start(arr, target, mid + 1, end)
def search_end(arr, target, start, end):
if start > end:
return -1
mid = (start + end) // 2
if (mid == n - 1 or arr[mid + 1] > target) and arr[mid] == target:
return mid
elif arr[mid] >= target:
return search_end(arr, target, start, mid - 1)
else:
return search_end(arr, target, mid + 1, end)
start_v = search_start(num, x, 0, n - 1)
end_v = search_end(num, x, 0, n - 1)
if start_v == end_v == -1:
print(-1)
else:
print(start_v - end_v + 1)
- 시작 인덱스와 끝 인덱스를 찾아서 빼주기
- 시작과 끝 함수에서 각각 어떻게 아래/위로 범위를 좁혀나갈지
: if (mid == 0 or arr[mid - 1] < target) and arr[mid] == target
과 if (mid == n - 1 or arr[mid + 1] > target) and arr[mid] == target