查找整数数组中循环的长度

时间:2016-04-13 05:56:12

标签: java arrays algorithm arraylist integer

所以我做了一个代码挑战,其中基本上是一个整数数组,其中每个索引中的值指向另一个索引。你的工作是在数组中找到一个循环的长度,只要你从数组中的索引0开始。

即:number = {1,3,0,1};索引0为1,它会引导您进入索引1,该索引为3,这将导致返回索引1,从而创建一个长度为2的循环。

我的问题是我的代码能够通过3/5测试用例,而且我无法在代码中发现可能导致错误的任何弱点。除了"测试用例n失败之外,我没有被告知我的预期,也没有任何其他信息!"

这是我的代码:

public static int answer(int[] numbers) {
    List<Integer> valuesUsed = new ArrayList<Integer>();
    int nextValue, currentValue = numbers[0];
    do {
        valuesUsed.add(currentValue);
        currentValue = (nextValue = numbers[currentValue]);
    } while (!valuesUsed.contains(currentValue));
    return valuesUsed.size();
}

编辑:

  • 数组大小将介于2到5000之间。

  • 我收到的测试用例是{1,3,0,1},{1,0},{1,2,1},其中我的代码正确传递。

2 个答案:

答案 0 :(得分:1)

我不确定它是否是唯一的错误,但您忘记将0添加到valuesUsed。这是您遇到的第一个索引,因此应该在循环之前将其添加到List中。

编辑:

更正:

当你关闭一个循环时,返回valuesUsed.size()是错误的,因为一些遇到的索引不是循环的一部分。

您应该返回valuesUsed.size()-valuesUsed.indexOf(currentValue)

例如,如果阵列是{1,3,1,4,2},则循环是1-> 3-> 4-> 2-> 1并且循环的长度是4 (第一个元素不计算在内)。

答案 1 :(得分:0)

试试这个

public static int answer(int[] numbers) {
    List<Integer> valuesUsed = new ArrayList<Integer>();
    int currentValue = 0;
    int nextValue =0; 
    do {
        currentValue = nextValue;
        nextValue = numbers[currentValue];
        valuesUsed.add(nextValue );

    } while (!valuesUsed.contains(currentValue));
    return valuesUsed.size();
}