java codility Frog-River-One

时间:2013-10-18 21:17:31

标签: java algorithm

我一直在尝试在Codility网页上解决Java练习。

以下是上述练习和我的解决方案的链接。

https://codility.com/demo/results/demoH5GMV3-PV8

任何人都可以告诉我在代码中可以更正哪些内容以提高分数吗?

以下是任务说明:

一只小青蛙想要到达河的另一边。青蛙目前位于0号位置,想要到达位置X.树叶从树上掉落到河面上。

给出一个非空零索引数组A,由表示落叶的N个整数组成。 A [K]表示一片叶子在时间K下降的位置,以分钟为单位测量。

目标是找到青蛙可以跳到河的另一边的最早时间。只有当叶子出现在从1到X的河对岸的每个位置时,青蛙才能穿过。

例如,给定整数X = 5和数组A,使得:

  A[0] = 1
  A[1] = 3
  A[2] = 1
  A[3] = 4
  A[4] = 2
  A[5] = 3
  A[6] = 5
  A[7] = 4

在第6分钟,一片叶子落到第5位。这是叶子出现在河对岸各个位置的最早时间。

写一个函数:

class Solution { public int solution(int X, int[] A); } 

给定一个由N个整数和整数X组成的非空零索引数组A,返回青蛙可以跳到河的另一边的最早时间。

如果青蛙永远不能跳到河的另一边,那么该函数应该返回-1。

例如,给定X = 5和数组A,使得:

  A[0] = 1
  A[1] = 3
  A[2] = 1
  A[3] = 4
  A[4] = 2
  A[5] = 3
  A[6] = 5
  A[7] = 4

该函数应返回6,如上所述。假设:

N and X are integers within the range [1..100,000];
each element of array A is an integer within the range [1..X].

复杂度:

expected worst-case time complexity is O(N);
expected worst-case space complexity is O(X), beyond input storage (not counting the storage required for input arguments).

可以修改输入数组的元素。

这是我的解决方案:

import java.util.ArrayList;
import java.util.List;

class Solution {

    public int solution(int X, int[] A) {
        int list[] = A;
        int sum = 0;
        int searchedValue = X;

        List<Integer> arrayList = new ArrayList<Integer>();

        for (int iii = 0; iii < list.length; iii++) {

            if (list[iii] <= searchedValue && !arrayList.contains(list[iii])) {
                sum += list[iii];
                arrayList.add(list[iii]);
            }
            if (list[iii] == searchedValue) {
                if (sum == searchedValue * (searchedValue + 1) / 2) {
                    return iii;
                }
            }
        }
        return -1;
    }
}

39 个答案:

答案 0 :(得分:33)

您在循环中使用arrayList.contains,这将不必要地遍历整个列表。

这是我的解决方案(我前段时间写过它,但我相信它得分为100/100):

    public int frog(int X, int[] A) {
        int steps = X;
        boolean[] bitmap = new boolean[steps+1];
        for(int i = 0; i < A.length; i++){
            if(!bitmap[A[i]]){
                bitmap[A[i]] = true;
                steps--;
            }
            if(steps == 0) return i;
        }
        return -1;
    }

答案 1 :(得分:11)

这是我的解决方案。它让我100/100:

public int solution(int X, int[] A)
{
     int[] B = A.Distinct().ToArray();
     return (B.Length != X) ? -1 : Array.IndexOf<int>(A, B[B.Length - 1]);
}

答案 2 :(得分:6)

使用集合(集合框架)的Java解决方案得到100%

import java.util.Set;
import java.util.TreeSet;
public class Froggy {
    public static int solution(int X, int[] A){
    int steps=-1;
    Set<Integer> values = new TreeSet<Integer>();
    for(int i=0; i<A.length;i++){
        if(A[i]<=X){
            values.add(A[i]);
        }
        if(values.size()==X){
            steps=i;
            break;
        }
    }
        return steps;
    }

答案 3 :(得分:5)

100/100

public static int solution (int X, int[] A){

    int[]counter = new int[X+1];
    int ans = -1;
    int x = 0;

    for (int i=0; i<A.length; i++){
        if (counter[A[i]] == 0){
            counter[A[i]] = A[i];
            x += 1;
            if (x == X){
                return i;
            }
        } 
    }

    return ans;
}

答案 4 :(得分:4)

更好的方法是使用Set,因为它只会为列表添加唯一值。只需在每次添加新值时向Set添加值并减少X,(Set#add()如果添加值则返回true,否则返回false; 看看,

public static int solution(int X, int[] A) {
    Set<Integer> values = new HashSet<Integer>();
    for (int i = 0; i < A.length; i++) {
        if (values.add(A[i])) X--; 
        if (X == 0) return i;
    }
    return -1;
}

不要忘记导入,

import java.util.HashSet;
import java.util.Set;

答案 5 :(得分:3)

简单解决方案100%

public int solution(final int X, final int[] A) {

Set<Integer> emptyPosition = new HashSet<Integer>();

for (int i = 1; i <= X; i++) {
  emptyPosition.add(i);
}
// Once all the numbers are covered for position, that would be the
// moment when the frog will jump
for (int i = 0; i < A.length; i++) {
  emptyPosition.remove(A[i]);
  if (emptyPosition.size() == 0) {
    return i;
  }
}
return -1;
}

答案 6 :(得分:2)

这是我的解决方案。 它并不完美,但足以获得100/100的分数。 (我认为它不应该通过大A和小X的测试)

无论如何,它会填充一个新的counter数组,每个叶子落下

计数器的大小为X,因为我不关心比X更远的叶子,因此是try-catch块。

在X叶子掉落之后(因为它是叶子的最小数量)我开始检查我是否有完整的方法 - 我正在检查计数中的每个int都大于0。 如果是这样,我会回来,否则我会再次尝试。

public static int solution(int X, int[] A){
    int[] count = new int[X];
    for (int i = 0; i < A.length; i++){
        try{
            count[A[i]-1]++;
        } catch (ArrayIndexOutOfBoundsException e){ }
        if (i >= X - 1){
            for (int j = 0; j< count.length; j++){
                if (count[j] == 0){
                    break;
                }
                if (j == count.length - 1){
                    return i;
                }
            }
        }
    }
    return -1;
}

答案 7 :(得分:2)

这是我的解决方案,得分为100/100:

import java.util.HashSet;

class Solution {
    public int solution(int X, int[] A) {
        HashSet<Integer> hset = new HashSet<Integer>();

        for (int i = 0 ; i < A.length; i++) {
            if (A[i] <= X)
               hset.add(A[i]);   
            if (hset.size() == X)
               return i;
        }

        return -1;
    }
}

答案 8 :(得分:2)

这是我100/100的解决方案。

public int solution(int X, int[] A) {
    int len = A.length;
    if (X > len) {
        return -1;
    }
    int[] isFilled = new int[X];
    int jumped = 0;
    Arrays.fill(isFilled, 0);
    for (int i = 0; i < len; i++) {
        int x = A[i];
        if (x <= X) {
            if (isFilled[x - 1] == 0) {
                isFilled[x - 1] = 1;
                jumped += 1;
                if (jumped == X) {
                    return i;
                }
            }
        }
    }

    return -1;
}

答案 9 :(得分:1)

%100 with js

function solution(X, A) {

  let leafSet = new Set();

  for (let i = 0; i < A.length; i += 1) {

    if(A[i] <= 0) 
        continue;

    if (A[i] <= X )
        leafSet.add(A[i]); 


    if (leafSet.size == X)
      return i;

  }

  return -1;
}

答案 10 :(得分:1)

使用JavaScript,以下解决方案获得了100/100。

检测到的时间复杂度:O(N)

function solution(X, A) {
    let leaves = new Set();

    for (let i = 0; i < A.length; i++) {
        if (A[i] <= X) {
            leaves.add(A[i])
            if (leaves.size == X) {
                return i;
            }
        }
    }
    return -1;    
}

答案 11 :(得分:1)

使用JavaScript的100%解决方案。

enter image description here

function solution(X, A) {
    if (A.length === 0) return -1
    if (A.length < X) return -1


    let steps = X
    const leaves = {}
    for (let i = 0; i < A.length; i++) {
        if (!leaves[A[i]]) {
            leaves[A[i]] = true
            steps--
        }

        if (steps === 0) {
            return i
        }
    }

    return -1
}

答案 12 :(得分:1)

得分为100%的C#解决方案:

using System;
using System.Collections.Generic;

class Solution {
    public int solution(int X, int[] A) {
        // go through the array
        // fill a hashset, until the size of hashset is X
        var set = new HashSet<int>();
        int i = 0;
        foreach (var a in A)
        {
            if (a <= X)
            {
                set.Add(a);
            }
            if (set.Count == X)
            {
                return i;
            }
            i++;
        }
        return -1;
    }
}

答案 13 :(得分:1)

这在100%的100%的共性中效果很好。它与上面的标记数组非常相似,但使用的是地图:

Sub formatrows()
    Dim rng1 As Range
    Dim rng2 As Range
    Dim row As Range
    Dim i As Integer
    Set rng1 = Range("Ac7:ao400")
    Set rng2 = Range("d7:d400")
    i = 0
    Range("AC7").Select
    'rng1.ClearFormats
    For Each row In rng1.Rows
        row.NumberFormat = ActiveCell.Offset(i, -25)
        i = i + 1
    Next row
End Sub

答案 14 :(得分:1)

这是我在Python中的答案:

def solution(X, A):
    # write your code in Python 3.6
    values = set()
    for i in range (len(A)):
        if A[i]<=X :
            values.add(A[i])
        if len(values)==X:
            return i
    return -1

答案 15 :(得分:1)

https://app.codility.com/demo/results/trainingXE7QFJ-TZ7/

我有一个使用 HashSet 的非常简单的解决方案 (100% / 100%)。很多人不必要地检查 Value 是否小于或等于 X。否则这个任务不可能。

public static int solution(int X, int[] A) {
    Set<Integer> availableFields = new HashSet<>();

    for (int i = 0; i < A.length; i++) {
        availableFields.add(A[i]);
        if (availableFields.size() == X){
            return i;
        }
    }

    return -1;
}

答案 16 :(得分:1)

实际上,我在没有看到我的最后答案的情况下重新编写了这个练习,并提出了另一个解决方案100/100和O(N)。

public int solution(int X, int[] A) {
    Set<Integer> leaves = new HashSet<>();

    for(int i=0; i < A.length; i++) {
        leaves.add(A[i]);

        if (leaves.contains(X) && leaves.size() == X)  return i; 
    }

    return -1;
}

我更喜欢这个,因为它更简单。

答案 17 :(得分:1)

这是我的解决方案

public func FrogRiverOne(_ X : Int, _ A : inout [Int]) -> Int {

    var B = [Int](repeating: 0, count: X+1)

    for i in 0..<A.count {
        if B[A[i]] == 0 {
            B[A[i]] = i+1
        }
    }

    var time = 0

    for i in 1...X {
        if( B[i] == 0 ) {
            return -1
        } else {
            time = max(time, B[i])
        }
    }

    return time-1
}

A = [1,2,1,4,2,3,5,4]
print("FrogRiverOne: ", FrogRiverOne(5, &A))

答案 18 :(得分:1)

下面是我的解决方案。我基本上创建了一个只允许单调的集合然后遍历数组并添加每个元素来设置并保持计数器以获得集合的总和然后使用连续数字的和公式然后我得到100%。注意:如果使用java 8 stream api添加集合,解决方案将变为二次方,您将获得%56。

public static int solution2(int X, int[] A) {

    long sum = X * (X + 1) / 2;
    Set<Integer> set = new HashSet<Integer>();
    int setSum = 0;

    for (int i = 0; i < A.length; i++) {
        if (set.add(A[i]))
            setSum += A[i];

        if (setSum == sum) {
            return i;
        }

    }

    return -1;
}

答案 19 :(得分:1)

这是我的解决方案,它让我100/100和O(N)。

public int solution(int X, int[] A) {
    Map<Integer, Integer> leaves = new HashMap<>();

    for (int i = A.length - 1; i >= 0 ; i--)
    {
        leaves.put(A[i] - 1, i);
    }

    return leaves.size() != X ? -1 : Collections.max(leaves.values());
}

答案 20 :(得分:1)

我今天发布的这个解决方案给出了100%的编码能力,但是@rafalio回答它需要K倍的内存

public class Solution {

    private static final int ARRAY_SIZE_LOWER = 1;
    private static final int ARRAY_SIZE_UPPER = 100000;
    private static final int NUMBER_LOWER = ARRAY_SIZE_LOWER;
    private static final int NUMBER_UPPER = ARRAY_SIZE_UPPER;

    public static class Set {

        final long[] buckets;

        public Set(int size) {
            this.buckets = new long[(size % 64 == 0 ? (size/64) : (size/64) + 1)];
        }

        /**
         * number should be greater than zero
         * @param number
         */
        public void put(int number) {
            buckets[getBucketindex(number)] |= getFlag(number); 
        }

        public boolean contains(int number) {
            long flag = getFlag(number);
            // check if flag is stored
            return (buckets[getBucketindex(number)] & flag) == flag;
        }

        private int getBucketindex(int number) {
            if (number <= 64) {
                return 0;
            } else if (number <= 128) {
                return 1;
            } else if (number <= 192) {
                return 2;
            } else if (number <= 256) {
                return 3;
            } else if (number <= 320) {
                return 4;
            } else if (number <= 384) {
                return 5;
            } else 
                return (number % 64 == 0 ? (number/64) : (number/64) + 1) - 1;
        }

        private long getFlag(int number) {
            if (number <= 64) {
                return 1L << number;
            } else
                return 1L << (number % 64);
        }
    }

    public static final int solution(final int X, final int[] A) {
        if (A.length < ARRAY_SIZE_LOWER || A.length > ARRAY_SIZE_UPPER) {
            throw new RuntimeException("Array size out of bounds");
        }
        Set set = new Set(X);
        int ai;
        int counter = X;
        final int NUMBER_REAL_UPPER = min(NUMBER_UPPER, X);
        for (int i = 0 ; i < A.length; i++) {
            if ((ai = A[i]) < NUMBER_LOWER || ai > NUMBER_REAL_UPPER) {
                throw new RuntimeException("Number out of bounds");
            } else if (ai <= X && !set.contains(ai)) {
                counter--;
                if (counter == 0) {
                    return i;
                }
                set.put(ai);
            }
        }
        return -1;
    }

    private static int min(int x, int y) {
        return (x < y ? x : y);
    }
}

答案 21 :(得分:1)

这是我的解决方案。我觉得这很简单。可达性为100/100。 set.contains()让我从表中删除重复的位置。 第一个循环的结果得到了我们预期的总和。在第二个循环中,我们得到输入值的总和。

class Solution {
    public int solution(int X, int[] A) {

        Set<Integer> set = new HashSet<Integer>();
        int sum1 = 0, sum2 = 0;

        for (int i = 0; i <= X; i++){
            sum1 += i;       
        }

        for (int i = 0; i < A.length; i++){
            if (set.contains(A[i])) continue;
            set.add(A[i]);
            sum2 += A[i];
            if (sum1 == sum2) return i;
        }        
        return -1;
    }
}

答案 22 :(得分:1)

也许它并不完美,但它很直白。只需制作一个计数器阵列来跟踪所需的“叶子”,并在每次迭代时验证路径是否完整。得到我100/100和O(N)。

    public static int frogRiver(int X, int[] A)
    {
        int leaves = A.Length;
        int[] counter = new int[X + 1];
        int stepsAvailForTravel = 0;

        for(int i = 0; i < leaves; i++)
        {
            //we won't get to that leaf anyway so we shouldnt count it,
            if (A[i] > X)
            {
                continue;
            } 
            else
            {
                //first hit!, keep a count of the available leaves to jump
                if (counter[A[i]] == 0)
                    stepsAvailForTravel++;

                counter[A[i]]++;

            }
            //We did it!!
            if (stepsAvailForTravel == X)
            {
                return i;
            }
        }

        return -1;

    }

答案 23 :(得分:1)

刚试过这个问题,这是我的解决方案。基本上,我刚刚声明了一个大小等于位置X的数组。然后,我宣布了一个计数器来监视必要的叶子是否落在特定的位置。当满足这些叶子时循环退出,如果没有,则按照指示返回-1。

class Solution {
    public int solution(int X, int[] A) {
        int size = A.length;
        int[] check = new int[X];
        int cmp = 0;
        int time = -1;

        for (int x = 0; x < size; x++) {
            int temp = A[x];
            if (temp <= X) {
                if (check[temp-1] > 0) {
                    continue;
                }
                check[temp - 1]++;
                cmp++;
            }

            if ( cmp == X) {
                time = x;
                break;
            }
        }

        return time;
    }
}

评估结果为100/100,但我对它的表现不太了解。在编程时我仍然是初学者,所以如果有人可以批评代码,我将不胜感激。

答案 24 :(得分:0)

另一种 C# 方法(类似于 Kamlesh Shewani 使用的方法):

using System;
using System.Collections.Generic;

class Solution {
        public int solution(int X, int[] A)
        {
            var set = new HashSet<int>(A);
            return set.Count != X ? -1 : Array.IndexOf<int>(A, new List<int>(set)[new List<int>(set).Count-1]);
        }
}

答案 25 :(得分:0)

 public static int solutions(int X, int[] A) {
        Set<Integer> values = new HashSet<Integer>();

        for (int i = 0; i < A.length; i++) {
            if (values.add(A[i])) {
                X--; 
            }
            if (X == 0) {
                return i;
            }
        }
        return -1;
    }

答案 26 :(得分:0)

HashSet<Integer> _hashset = new HashSet<Integer>();
        int occupiedPositions = 0;

        for (int i = 0; i < A.length; i++)
        {
            if(A[i] <= X && _hashset.add(A[i]))
            {
                occupiedPositions++;
            }

            if (occupiedPositions == X)
                return i;
        }

        return -1;

}

答案 27 :(得分:0)

我认为此解决方案很容易理解。 如果需要了解详细点。请让我知道您想知道哪一部分。

    static int solution(int x, int[]a){

    int currentPosition = 0;//The frog is initially located on one bank of the river (position 0) 
    int[] opositPostion = new int[x+1];//wants to get to the opposite bank (position X+1). 

    for(int i = 0; i < a.length; i++){

        if (opositPostion[a[i]]== 0){
            opositPostion[i] = a[i];
            currentPosition += 1;
        }
        if (currentPosition == x){//The goal is to find the earliest time when the frog can jump to the other side of the river.
            return i;
        }
    }

    return -1;

}

答案 28 :(得分:0)

这是一个独特的解决方案[上面在C ++中使用多图尚未列出]。 这在codility上得分为100%,并且检测到的big(O)复杂度为O(N)。本质上可以构建位置和位置列表的多张地图(例如,几秒钟内叶子落在该位置的时间)。

int solution(int targetPos, vector<int>& A)
{
  if(!A.size())
    return(-1);

  multimap<int, int> positionMap;
  bool insertStatus=false;
  for(size_t i=0;i<A.size();++i)
  {
    positionMap.insert(pair<int, int>(A[i], i));
    if(targetPos==A[i])
      insertStatus=true;
  }

  if(!insertStatus)
    return(-1);

  int currMax=-1;
  for(int i=1; i<=targetPos;++i)
  {
    auto iter=positionMap.equal_range(i);
    if(!distance(iter.first, iter.second))
      return(-1);

    int currMin=INT_MAX;
    for(auto it=iter.first; it!=iter.second; ++it)
    {
      if(it->second<currMin)
        currMin=it->second;
    }
    if(currMin>currMax)
      currMax=currMin;
  }

  return(currMax);
}

答案 29 :(得分:0)

在 Java 中使用哈希集的另一个答案,得分为 100/100。

    public int solution(int X, int[] A) {            
        Set<Integer> positions = new HashSet<>();
        for(int i = 0; i < A.length; i++){
            if(A[i] <= X)
                positions.add(A[i]);
            if(positions.size() == X)
                return i;
        }
        return -1;
    }

答案 30 :(得分:0)

Frogt Reiver One Codility 10%

在python编译率100%中几乎没有解释

def solution(X, A):
"""
https://app.codility.com/demo/results/trainingQ28RU6-FFE/
100%
idea is use array item as K_index in covered time array
covered time array set the value to be covered as soon as it finds some value
if position is already covered it checks for all items in array until any of the item in array can be covered
:param X:
:param A:
:return:
"""
# assume all position is covered
covered_time = [-1] * X
for K_index in range(0, len(A)):
    print("Covered position count " + str(X))
    print(X)
    print(covered_time)
    if covered_time[A[K_index] - 1] != -1:
        # A[K] represents the position where one leaf falls at time K
        # position is already covered
        # time is being spent
        continue
    else:
        # This position is to be covered
        # cover this position ie. make array element with marker(array value)
        covered_time[A[K_index] - 1] = K_index
        # reduce position to be cover
        X -= 1
        # as soon as positions are covered return
        if X == 0:
            # now all positions are covered
            return K_index
# if we are here it means time spent but we can not cover all positions
return -1


result = solution(5, [1, 3, 1, 4, 2, 3, 5, 4])
print("Sol " + str(result))

答案 31 :(得分:0)

还有Java的100%得分:

class Solution {
    public int solution(int X, int[] A) {
        int leafs[] = new int[X];
        int count = X;
        for (int i = 0; i < A.length; i++)
        {   
            if (leafs[A[i]-1] != 1)
            {
                leafs[A[i]-1] = 1;
                count--;
            }
            if (count == 0)
                return i;
        }
        return -1;
    }
}

答案 32 :(得分:0)

这将循环数组A并将数据插入数组B(1)到A中的内容所指向的每个位置。

如果A [0] = 4,则在B [4-1] = 1时执行此操作,直到var =X。

public static int bestSolution(int X, int[] A) {
        int[] B = new int[X];
        int var = 0;
        for (int i = 0; i < A.length; i++) {
            int content = A[i];
            if (B[content - 1] == 0) {
                B[content - 1] = 1;
                var++;
            }
            if(var == X){
                return i;
            }
        }
        return -1;
    }

答案 33 :(得分:0)

我的JavaScript解决方案全面实现了100个。由于假定数字在河流宽度范围内,因此只需将布尔值存储在可以检查重复项的临时数组中即可。然后,一旦您积累了数量X一样多的数字,就知道您已经拥有了所有需要交叉的叶子。

function solution(X, A) {
    covered = 0;
    tempArray = [];
    for (let i = 0; i < A.length; i++) {
        if (!tempArray[A[i]]) {
            tempArray[A[i]] = true;
            covered++
            if(covered === X) return i;
        }
    }
    return -1;
}

答案 34 :(得分:0)

import java.util.Set;
import java.util.HashSet;
// you can write to stdout for debugging purposes, e.g.
// System.out.println("this is a debug message");

class Solution {
    public int solution(int X, int[] A) {
     Set<Integer> positionsCovered = new HashSet<Integer>(); 
//Set covering the leaves fallen to keep track of the distance to destination   

        if(X == 1)
             return 0 ;
       int position = 0;     
       for(int i = 0; i < A.length -1 ;i++ ) {       
           if(A[i] <= X && A[i] > 1 && positionsCovered.size() < (X-1)) { 
      //X-1 as we start from 1
               positionsCovered.add(A[i]);
           }
           if(positionsCovered.size()== (X-1)) {
               position = i ;
            break;
           }
       }         
        return position != 0 ? position : -1;
    }
}

答案 35 :(得分:0)

简短而又甜蜜的C ++代码。完美100%...鼓声...... enter image description here

#include <set>
int solution(int X, vector<int> &A) {
    set<int> final;
    for(unsigned int i =0; i< A.size(); i++){
        final.insert(A[i]);
        if(final.size() == X) return i;
    }
    return -1;
}

答案 36 :(得分:0)

这是我的解决方案。它使用3个循环但是是恒定时间,并且在可行性方面得到100/100。

class FrogLeap
{
    internal int solution(int X, int[] A)
    {
        int result = -1;
        long max = -1;
        var B = new int[X + 1];

        //initialize all entries in B array with -1
        for (int i = 0; i <= X; i++)
        {
            B[i] = -1;
        }

        //Go through A and update B with the location where that value appeared
        for (int i = 0; i < A.Length; i++)
        {
           if( B[A[i]] ==-1)//only update if still -1
            B[A[i]] = i;
        }

        //start from 1 because 0 is not valid
        for (int i = 1; i <= X; i++)
        {
            if (B[i] == -1)
                return -1;
            //The maxValue here is the earliest time we can jump over
            if (max < B[i])
                max = B[i];
        }

        result = (int)max;
        return result;
    }
}

答案 37 :(得分:-1)

JavaScript解决方案

function solution(X, A) {
    // write your code in JavaScript (Node.js 8.9.4)
    let minTime = -1;
    
    //initial positions with leafs
    let posFilled = Array(X+1).fill(false);
    let totalFilled = 0;

    for(let i=0; i<A.length; i++){
        let step = A[i];
        
        //if already filled, don't add to total filled
        if(step <= X && !posFilled[step]) {
            posFilled[step] = true;
            
            //increment total filled
            totalFilled += 1;
        }

        //if all have been filled, set min time and break        
        if(totalFilled === X){
            minTime = i;
            
            break;
        }
    }
    
    return minTime;
}

答案 38 :(得分:-1)

 private static int FrogRiverOne(int X, int[] A)
        {
            HashSet<int> occ = new HashSet<int>();
            for (int i = 0; i < A.Length; i++)
            {
                if (A[i] <= X)
                {
                    occ.Add(A[i]);
                }
                if (occ.Count == X)
                    return i;
            }
            return -1;}