基于Python的编码带平衡训练

2024-04-18 01:11:41 发布

您现在位置: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)。 谁能给我建议一下吗?在


Tags: andoftheismylistemptyfirst
3条回答

您可以将您的代码更改为类似下面这样的代码,以使其具有复杂性O(N)。在

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

我的java代码 O(N)

class Solution {
public int solution(int[] arr) {

   int sum = 0;

   for(int i = 0; i<arr.length; i++){
       sum = sum + arr[i];
   }



  int  minSum = 100000;
  int  tempSum = 0;
  int previousSum = 0;
   for(int i = 0; i<arr.length-1; i++){

       previousSum = previousSum + arr[i];

      tempSum = Math.abs(previousSum - (sum - previousSum));

      if(minSum > tempSum){
          minSum = tempSum;
      }


   }

   return minSum;
}

}

为了回答您的问题,它是O(n*n),因为sum()函数是O(n)时间复杂度,并且您在一个for循环中调用它,这个循环也是O(n)。在

因此算法的时间复杂度为O(N*N)

相关问题 更多 >

    热门问题