FrogRiverOne
🔗 문제 링크
https://app.codility.com/programmers/lessons/4-counting_elements/frog_river_one/start/
❔ 문제 설명
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.
⚠️ 제한사항
-
N and X are integers within the range [1..100,000];
-
each element of array A is an integer within the range [1..X].
💡 풀이 (언어 : Java & Python)
쉽게 풀었다. set를 이용해서 중복값을 없애주며 나온 숫자를 넣어준다. 조건에서 등장하는 숫자는 범위가 X이하라고 했으므로, set의 길이가 X가 되는 순간이 바로 1부터 X까지 숫자들이 모두 등장하는 순간이다. 시간 복잡도는
Java
import java.util.HashSet;
class Solution {
public int solution(int X, int[] A) {
HashSet<Integer> set = new HashSet<>();
for (int i = 0; i < A.length; i++) {
set.add(A[i]);
if (set.size() == X)
return i;
}
return -1;
}
}
Python
def solution(X, A):
# A의 위치 값들의 중복을 제거하기 위한 set 선언
check = set()
for i in range(len(A)):
check.add(A[i])
# 도중에 check의 길이가 X와 같아지면 모든 나뭇잎이 채워졌으므로 i=시간초 반환
if len(check) == X:
return i
# for문을 다 돌았는데도 함수가 안끝났으면 못가는 케이스이므로 -1 반환
return -1
Author And Source
이 문제에 관하여(FrogRiverOne), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@shiningcastle/FrogRiverOne저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)