Random commentary about Machine Learning, BigData, Spark, Deep Learning, C++, STL, Boost, Perl, Python, Algorithms, Problem Solving and Web Search
What about the below C++ code? Does that count as a solution? It returns -1, if no such index exists (I have not tested it, though :))====int equilibrium(const int *a, const int n){ int sumRight = 0; for (int i = 0; i < n; ++i) sumRight += a[i]; int j, sumLeft = 0; for (j = 0; j < n; ++j) { if (sumLeft == sumRight) break; sumLeft += a[j]; sumRight -= a[j]; } return (j == n-1)?-1:j;}
are you assuming it is sorted?
What about the below C++ code? Does that count as a solution? It returns -1, if no such index exists (I have not tested it, though :))
ReplyDelete====
int equilibrium(const int *a, const int n)
{
int sumRight = 0;
for (int i = 0; i < n; ++i) sumRight += a[i];
int j, sumLeft = 0;
for (j = 0; j < n; ++j) {
if (sumLeft == sumRight) break;
sumLeft += a[j];
sumRight -= a[j];
}
return (j == n-1)?-1:j;
}
are you assuming it is sorted?
ReplyDelete