A non-empty zero-indexed array A consisting of N integers is given. Array A represents numbers on a tape. Any integer P, such that 0 < P < N, splits this tape into two non-empty parts: A[0], A[1], ..., A[P − 1] and A[P], A[P + 1], ..., A[N − 1]. The difference between the two parts is the value of: |(A[0] + A[1] + ... + A[P − 1]) − (A[P] + A[P + 1] + ... + A[N − 1])| In other words, it is the absolute difference between the sum of the first part and the sum of the second part.
def solution(A):
N = len(A)
my_list = []
for i in range(1, N):
first_tape = sum(A[:i - 1]) + A[i]
second_tape = sum(A[i - 1:]) + A[i]
difference = abs(first_tape - second_tape)
my_list.append(difference)
print(min(my_list))
return min(my_list)
我的解决方案的正确率为100%,但性能为0%。 我想应该是O(N),但我的时间复杂度是O(N*N)。 谁能给我建议一下吗?在
您可以将您的代码更改为类似下面这样的代码,以使其具有复杂性
O(N)
。在我的java代码 O(N)
}
为了回答您的问题,它是O(n*n),因为
sum()
函数是O(n)时间复杂度,并且您在一个for
循环中调用它,这个循环也是O(n)。在因此算法的时间复杂度为O(N*N)
相关问题 更多 >
编程相关推荐