【发布时间】:2015-08-03 10:56:29
【问题描述】:
这是一项来自代码的任务,需要 O(n) 复杂度。虽然我已经解决了它给出正确结果的任务,但时间复杂度是 O(n*n)。在解释如何将复杂性降低到 O(n) 时,我们将不胜感激。
任务描述:
给出了一个由 N 个整数组成的非空零索引数组 A。 数组 A 代表磁带上的数字。
任何整数 P,例如 0
两部分的区别在于:|(A[0] + A[1] + ... + A[P - 1]) - (A[P] + A[P + 1] + ... + A[N - 1])|
换句话说,它是总和之间的绝对差 第一部分和第二部分的总和。
例如,考虑数组 A,这样:
A[0] = 3 A[1] = 1 A[2] = 2 A[3] = 4 A[4] = 3
我们可以把这个磁带分成四个地方:
P = 1, difference = |3 − 10| = 7 P = 2, difference = |4 − 9| = 5 P = 3, difference = |6 − 7| = 1 P = 4, difference = |10 − 3| = 7写一个函数:
int solution(vector<int> &A);给定一个由 N 个整数组成的非空零索引数组 A,返回 可以达到的最小差异。
例如,给定:
A[0] = 3 A[1] = 1 A[2] = 2 A[3] = 4 A[4] = 3
该函数应返回 1,如上所述。
假设:
N is an integer within the range [2..100,000]; each element of array A is an integer within the range [−1,000..1,000].复杂性:
expected worst-case time complexity is O(N); expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).输入数组的元素可以修改。
My solution:
int solution(vector<int>& A)
{
// write your code in C++11
int result = std::numeric_limits<int>::max();
int part_1 = 0;
int part_2 = 0;
for (auto beg = A.cbegin(), end = A.cend(); beg != prev(end); ++beg)
{
part_1 = accumulate(A.cbegin(),beg + 1,0);
part_2 = accumulate(beg + 1,end,0);
int current_result = abs(part_1 - part_2);
if (current_result < result)
{
result = current_result;
}
}
return result;
}
【问题讨论】:
-
我认为任务中有一个小错误 - 它说“0