python - Codility - 使用 Python 进行磁带平衡训练

标签 python

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)。 任何人都可以给我建议吗?

最佳答案

您可以将您的代码更改为类似下面的代码以具有复杂性ON)

def solution(A):          
    s = sum(A)
    m = float('inf')
    left_sum = 0
    for i in A[:-1]:
        left_sum += i
        m = min(abs(s - 2*left_sum), m)
    return m

关于python - Codility - 使用 Python 进行磁带平衡训练,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48030130/

相关文章:

python - 在Python中删除CSR格式矩阵的列

python - 创建 django 表单对象并保存

python - python中xml的GetTreeNode

python - 使用 subprocess.Popen 恢复进程?

python - matplotlib 可拖动图例在 Mac OS 10.8 上不可用吗?

python - 如何在 DataFrame 中的每一行上运行函数并将结果附加到新的 DataFrame

python - 在谷歌域上为 heroku 应用程序强制使用 HTTPS

python - 使用 uvicorn 运行时,fastapi 找不到模型定义

python - 列出字典中元组键的所有值

python - 如何访问更改状态的按钮