A small frog wants to get to the other side of a river. The frog is initially located on one bank of the river (position 0) and wants to get to the opposite bank (position X+1). Leaves fall from a tree onto the surface of the river.
You are given an array A consisting of N integers representing the falling leaves. A[K] represents the position where one leaf falls at time K, measured in seconds.
The goal is to find the earliest time when the frog can jump to the other side of the river. The frog can cross only when leaves appear at every position across the river from 1 to X (that is, we want to find the earliest moment when all the positions from 1 to X are covered by leaves). You may assume that the speed of the current in the river is negligibly small, i.e. the leaves do not change their positions once they fall in the river.
For example, you are given integer X = 5 and array A such that:
A[0] = 1
A[1] = 3
A[2] = 1
A[3] = 4
A[4] = 2
A[5] = 3
A[6] = 5
A[7] = 4
In second 6, a leaf falls into position 5. This is the earliest time when leaves appear in every position across the river.
Write a function:
def solution(X, A)
that, given a non-empty array A consisting of N integers and integer X, returns the earliest time when the frog can jump to the other side of the river.
If the frog is never able to jump to the other side of the river, the function should return −1.
For example, given X = 5 and array A such that:
A[0] = 1
A[1] = 3
A[2] = 1
A[3] = 4
A[4] = 2
A[5] = 3
A[6] = 5
A[7] = 4
the function should return 6, as explained above.
Write an efficient algorithm for the following assumptions:
N and X are integers within the range [1..100,000];
each element of array A is an integer within the range [1..X].
문제를 잘못 읽어버리는 바람에 처음에는 문제 접근이라고 말할 만한게 없다. 처음에는 주어진 X에 해당하는 초를 출력하는 엄청나게 간단한 문제인 줄 알고 계속해서 풀었기 때문...(그렇게 간단할리가 없지만)
두번째 시도만에 문제를 잘못 읽었다는 것을 인지했고 다시 문제를 읽어 주어진 X까지 순서대로 잎을 밟고 X까지 도달할 수 있는 최소 시간을 구하는 문제였던 거이였다!
그래서 집합을 통해 add해도 겹치는 숫자는 들어가지 않는 성질을 이용해 풀어보기로 했다.
def solution(X, A):
for i in range(len(A)):
if(A[i]==X):
return i
return -1
이때까지 전혀 인지 하지 못했음.
def solution(X, A):
num =0
for i in range(len(A)):
if(A[i] == X):
num = i
break
if(num==0):
return -1
else:
return num
첫번째 풀었던 것보다 더 자세하게 풀었을 텐데 더 낮은 점수에 이상함을 자각했다.
def solution(X, A):
leaves = set()
for i in range(len(A)):
if(len(leaves)==X): return i-1
if(A[i] not in leaves):
leaves.add(A[i])
문제를 다시 읽고 문제를 다시 풀어봤다. 정제되지 않은 코드에다가 건너편으로 건너가지 못하면 -1을 출력하라는 조건도 지키지 않아서 63%가 나왔지만 그래도 점수가 많이 높아졌다는 것에 이제 문제를 올바르게 인지하고 있다는 확신을 가졌다.
def solution(X, A):
leaves = set()
for i in range(len(A)):
if A[i] <= X:
leaves.add(A[i])
if len(leaves_positions) == X: return i
return -1
충족시키지 않았던 조건을 추가하고 A[i]가 X보다 큰 경우는 전부 무시했다. 같거나 작은 경우 집합을 사용했기 때문에 겹치는 값은 들어가지 않는다.
휴! 다행이다.
쉬웠던 문제였지만 문제를 잘못읽는 바람에 엄청 많이 돌아갔던 문제였던것 같다. 만약 실전에서 이런다면 정말 아찔한 상황일것...
정확도에 문제가 있으면 문제랑 조건 한번씩 더 확인해보자...