-
[이코테 이진 탐색] 고정점 찾기Coding Test/이것이 코딩 테스트다 2021. 1. 10. 04:18
# 문제
고정점(Fixed Point)이란, 수열의 원소 중에서 그 값이 인덱스와 동일한 원소를 의미합니다. 예를 들어 수열 a = {-15, -4, 2, 8, 13}이 있을 때 a[2]=2이므로, 고정점은 2가 됩니다.
하나의 수열이 N개의 서로 다른 원소를 포함하고 있으며, 모든 원소가 오름차순으로 정렬되어 있습니다. 이때 이 수열에서 고정점이 있다면, 고정점을 출력하는 프로그램을 작성하세요. 만약 고정점이 없다면 -1을 출력합니다.
단, 이 문제는 시간 복잡도 O(logN)으로 알고리즘을 설계하지 않으면 '시간 초과' 판정을 받습니다.# 입력
- 첫째 줄에 N이 입력됩니다. (1 ≤ N ≤ 1,000,000)
- 둘째 줄에 N개의 원소가 정수 형태로 공백으로 구분되어 입력됩니다. (-10^9 ≤ 각 원소의 값 ≤ 10^9)
# 출력
- 고정점을 출력한다. 고정점이 없다면 -1을 출력합니다.
# 입력 예시
# 입력 예시 1 5 -15 -6 1 3 7 # 입력 예시 2 7 -15 -4 2 8 9 13 15 # 입력 예시 3 7 -15 -4 3 8 9 13 15
# 출력 예시
# 출력 예시 1 3 # 출력 예시 2 2 # 출력 예시 3 -1
내 풀이
def binary_search(array, start, end): while start <= end: mid = (start + end) // 2 # 고정점을 찾은 경우 if array[mid] == mid: return mid # 중간점의 값이 중간점보다 큰 경우 왼쪽 확인 elif array[mid] > mid: end = mid - 1 # 중간점의 값이 중간점보다 작은 경우 오른쪽 확인 else: start = mid + 1 return -1 # 고정점이 없는 경우 -1 반환 n = int(input()) numbers = list(map(int, input().split())) print(binary_search(numbers, 0, n - 1))
'Coding Test > 이것이 코딩 테스트다' 카테고리의 다른 글
[이코테 다이나믹 프로그래밍] 개미 전사 (0) 2021.01.10 [이코테 다이나믹 프로그래밍] 1로 만들기 (0) 2021.01.10 [이코테 이진 탐색] 정렬된 배열에서 특정 수의 개수 구하기 (0) 2021.01.10 [이코테 이진 탐색] 떡볶이 떡 만들기 (0) 2021.01.10 [이코테 이진 탐색] 부품 찾기 (0) 2021.01.10