我正在训练Codility解决第一课:Tape-Equilibrium
。
据说它必须具有复杂性O(N)。因此,我试图用一个for
来解决问题。我知道如何使用两个for
来完成它,但我知道它会暗示O(2N)的复杂性,因此我跳过了这些解决方案。
我在互联网上寻找它,当然还有in SO there was an answer
令我惊讶的是,所有解决方案首先计算向量元素的总和,然后进行计算。我知道这是复杂度O(2N),但得分为100%。
此时,我认为我对时间复杂性限制的理解是错误的。如果他们要求你得到O(N)的时间复杂度,那么得到O(X * N)是正确的吗? X值不是很高吗?
这是如何运作的?
答案 0 :(得分:2)
让f
和g
成为函数
Big-O表示法f in O(g)
表示您可以找到c
的常数f(n) ≤ c⋅g(n)
。因此,如果您的算法具有复杂度2N
(或XN
对于常量X
),由于O(N)
(或c = 2
),此算法位于c = X
持有2N ≤ c⋅N = 2⋅N
(或XN ≤ c⋅N = X⋅N
)。
答案 1 :(得分:0)
这就是我设法保持O(N)以及100%得分的方式:
// you can also use imports, for example:
// import java.util.*;
// you can use System.out.println for debugging purposes, e.g.
// System.out.println("this is a debug message");
class Solution {
public int solution(int[] A) {
int result = Integer.MAX_VALUE;
int[] s1 = new int[A.length-1];
int[] s2 = new int[A.length-1];
for(int i=0;i<A.length-1;i++){
if(i>0){
s1[i] = s1[i-1] + A[i];
}
else {
s1[i] = A[i];
}
}
for(int i=A.length-1;i>0;i--){
if(i<A.length-1){
s2[i-1] = s2[i] + A[i];
}
else {
s2[i-1] = A[A.length-1];
}
}
for(int i=0;i<A.length-1;i++){
if(Math.abs(s1[i]-s2[i])<result){
result = Math.abs(s1[i]-s2[i]);
}
}
return result;
}
}