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.
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].
이 문제의 핵심은 1 ~ X 까지의 수가 모두 등장했을 때의 최소 index 를 찾는 문제이다. 즉, 1 ~ X 까지로 이루어진 Set 을 만들고 하나씩 배열 A 의 원소들로 remove 하면서 원소가 모두 사라졌을 때의 index 가 최솟값이 된다.
따라서, O(N) 시간 복잡도로 간단하게 구현할 수 있다.
import java.util.*;
class Solution {
public int solution(int X, int[] A) {
HashSet<Integer> set = new HashSet<>();
for(int i = 1; i <= X; i++){
set.add(i);
}
for(int j = 0; j < A.length; j++){
set.remove(A[j]);
if(set.size() == 0){
return j;
}
}
return -1;
}
}
'Algorithm' 카테고리의 다른 글
[Codility] MissingInteger (1) | 2019.05.30 |
---|---|
[Codility] MaxCounters (0) | 2019.05.30 |
[Codility] PermCheck (0) | 2019.05.30 |
[Codility] PermMissingElem (0) | 2019.05.30 |
[Codility] FrogJmp (0) | 2019.05.30 |