`

Codility - Earliest Time Frog Crossing River

 
阅读更多

Question:

A small frog wants to get to the other side of a river. The frog is currently located at position 0, and wants to get to position X. Leaves fall from a tree onto the surface of the river. You are given a non-empty zero-indexed array A consisting of N integers representing the falling leaves. A[K] represents the position where one leaf falls at time K, measured in minutes. 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.

 

Solution:

public int solution(int X, int[] A) {
    boolean[] tiles = new boolean[X];
    int todo = X;

    for (int i = 0; i < A.length; i++) {
        int internalIndex = A[i] - 1;
        if (!tiles[internalIndex]) {
            todo--;
            tiles[internalIndex] = true;
        }

        if (todo == 0)
            return i;
    }

    return -1;
}

This algorithm only requires O(n) time, since it always keeps track of how many "holes" we still have to fill with leaves.

 

todo is the number of leaves still required to build the "bridge" of leaves. Whenever a leaf falls down, we first check whether there not already is a leaf at the position it falls down. If not, we decrement todo, fill the hole and go on. As soon as todo reaches 0, the entire river is covered ;) 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics