提高竞争性编程问题的表现

时间:2019-10-08 20:03:56

标签: java arrays algorithm

在串联电路中,从1到N的N个灯泡。数组表示从0到(N-1)的灯泡编号。最初,所有灯泡均已关闭,并从阵列的索引0打开。我们需要计算在串联电路中打开灯泡的次数。

例如:

A = [2,1,3,5,4]应该返回3

Explanation :-
Instant     Bulb number on      All bulbs in series switched on
0               2                   false
1               1,2                 true
2               1,2,3               true
3               1,2,3,5             false
4               1,2,3,4,5           true

因此,有3种情况下灯泡已打开。计数为3。

我的方法

  1. 遍历数组的索引
  2. 将数组的切片从0移到索引
  3. 排序数组
  4. 检查数组是否已打开从0到index-1的所有灯泡
  5. 计算实例数。

我的解决方案运行得很好,但是时间复杂度为O(n2)。我的解决方法如下

public int solution(int[] A) {
    // write your code in Java SE 8
    int counter = 0;

    for (int i = 0; i < A.length; i++) {
        int[] intermediate = Arrays.copyOfRange(A, 0, i);
        Arrays.sort(intermediate);

        if(checkIfOrdered(intermediate))
            counter++;
    }
    return counter;
}

private static boolean checkIfOrdered(int[] intermediate) {
    boolean flag = true;
    for (int i = 0; i < intermediate.length; i++) {
        if(intermediate[i] != (i +1) ){
            flag = false;
            break;
        }
    }
    return flag;
}

有人可以指出如何改善我的代码的性能吗? 任何指针都将非常有帮助!!!

2 个答案:

答案 0 :(得分:5)

遇到这些问题,有时可以通过不同地计算答案来消除一些所需的循环。

在您的示例中,每个时刻似乎唯一需要的信息是灯泡的数量以及迄今为止找到的最大灯泡数量。

例如:

  • 在瞬间1,有2个灯泡亮着,其中2个是最大数量。
  • 在瞬间3,有3个灯泡亮着,其中3个是最大的。
  • 在第4瞬间,有5个灯泡亮着,其中5个是最大的。

答案是最大数量等于灯泡上的灯泡的数量。

答案 1 :(得分:0)

@fgb指示了一个简单的标准:当true时将为max == count

然后,您只需要计算最大值和计数值即可。

public static int solution(int [] xs) {

    int max = xs[0];
    int count = 0;

    int trues = 0;

    for(int x: xs) {

        max = Math.max(max, x);
        count = count + 1;

        if(max == count)
            trues = trues + 1;

    }

    return trues;

}