A[0] + A[1] + ... + A[P−1] = A[P+1] + ... + A[N−2] + A[N−1].
0 ≤ P < N
P 即为所求
数组中只有一个值可满足, 返回为0; 如找不到返回-1;
时间 空间复杂度都为o(n)
#include<stdio.h>
int solution(int A[], int N) {// write your code here...
if (N<1)
return -1;
long long sum = 0;
long long sumLeft =0;
int i;
for (i = 0; i < N; i++){
sum += (long long)A[i];
}
for (i = 0; i < N; i++){
if (sumLeft == sum - sumLeft - A[i]){
return i;
}
sumLeft += (long long)A[i];
}
return -1;
}
void main(){
int A[7] = {-7, 1, 5, 2, -4, 3, 0};
printf("res = %d\n", solution(A,7));
}
时间复杂度是o(n**2)
int solution(int A[], int N) { // write your code here... int i, l, k; long long sumPre; long long sumLast; for (i=0; i < N; i++){ sumPre =0; sumLast =0; for (l = 0; l < i; l++){ sumPre += (long long)A[l]; } for (l = i+1; l<N ; l++){ sumLast += (long long)A[l]; } if (sumPre == sumLast) return i; } return -1; }