C程序,查找要删除的子数组的起始索引和结尾索引,以使给定数组的左侧和右侧的总和相等。如果无法打印-1。我需要它可用于任何阵列,这仅用于测试。这是找到平衡的代码。
#include <stdio.h>
int equilibrium(int arr[], int n)
{
int i, j;
int leftsum, rightsum;
/* Check for indexes one by one until
an equilibrium index is found */
for (i = 0; i < n; ++i) {
/* get left sum */
leftsum = 0;
for (j = 0; j < i; j++)
leftsum += arr[j];
/* get right sum */
rightsum = 0;
for (j = i + 1; j < n; j++)
rightsum += arr[j];
/* if leftsum and rightsum are same,
then we are done */
if (leftsum == rightsum)
return i;
}
/* return -1 if no equilibrium index is found */
return -1;
}
// Driver code
int main()
{
int arr[] = { -7, 1, 5, 2, -4, 3, 0 };
int arr_size = sizeof(arr) / sizeof(arr[0]);
printf("%d", equilibrium(arr, arr_size));
getchar();
return 0;
}
答案 0 :(得分:1)
您可以在O(NlogN)
或O(N)
(通常情况下)中解决此问题。
首先,您需要进行预处理,将所有总和从右到左保存在数据结构中,尤其是平衡的二进制搜索树(例如Red Black tree,AVL树,Splay树等,如果您可以使用stdlib
,只需使用std::multiset
)或HashTable(在stdlib
中是std::unordered_multiset
):
void preProcessing(dataStructure & ds, int * arr, int n){
int sum = 0;
int * toDelete = (int) malloc(n)
for(int i = n-1; i >= 0; --i){
sum += arr[i];
toDelete[i] = sum; // Save items to delete later.
tree.insert(sum);
}
因此,要解决问题,您只需遍历数组一次:
// It considers that the deleted subarray could be empty
bool Solve(dataStructure & ds, int * arr, int n, int * toDelete){
int sum = 0;
bool solved = false; // true if a solution is found
for(int i = 0 ; i < n; ++i){
ds.erase(toDelete[i]); // deletes the actual sum up to i-th element from data structure, as it couldn't be part of the solution.
// It costs O(logN)(BBST) or O(1)(Hashtable)
sum += arr[i];
if(ds.find(sum)){// If sum is in ds, then there's a leftsum == rightsum
// It costs O(logN)(BBST) or O(1)(HashTable)
solved = true;
break;
}
}
return solved;
}
然后,如果您使用BBST(平衡二进制搜索树),则您的解决方案将为O(NlogN)
,但是,如果您使用HashTable,则您的解决方案将平均为O(N)
。我不会实现它,所以也许有一个错误,但是我尝试解释主要思想。