본문으로 바로가기

Description

아래의 설명에 따라 X까지 도달하기 위해 1~X까지의 모든 숫자가 배열의 요소에 존재하는 가장 낮은 값을 찾는 문제입니다. 모든 숫자가 없어 다리를 건너지 못하면 -1를 반환합니다.

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:

class Solution { public int solution(int X, int[] 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].

Solution 1. Using Set

public int solution(int X, int[] A) {
    int len = A.length;
    Set<Integer> set = new HashSet<>();
    for (int i = 1; i <= X; i++) {
        set.add(i);
    }

    for(int i =0; i<len; i++){
        set.remove(A[i]);
        if(set.isEmpty()){
            return i;
        }
    }
    return -1;
}

Set을 이용해서 가야하는 1~X까지의 나뭇잎 포지션을 모두 넣어두고 배열의 요소를 만날때마다 제외해줍니다. set이 빌경우 모든 위치가 다 있는 것이기때문에 해당 index(i)를 반환하고 모든 배열의 요소를 순환해도 set을 비울 수 없으면 -1를 반환합니다.

Reference

 

FrogRiverOne coding task - Learn to Code - Codility

Find the earliest time when a frog can jump to the other side of a river.

app.codility.com

String, Hash Table, LinkedList, Depth-First Search, Breadth-First Search, Matrix, TwoPoint, Array, Recusion,

Binary Tree, Recusion, 전위순회, inorder-traversal