Reputation: 145
I'm trying to think of an efficient algorithm that solves the following problem:
Given an array of integers, return the index of the element in the array that equals to the sum of the remaining elements in the array; if no such element exists, return -1.
For example, given the array of [1,2,3,6]
, then return 4 since 6=1+2+3;
given [3, -3, 5, 1]
, return 0 since 3 = -3 + 5 + 1
.
Any thoughts?
Upvotes: 0
Views: 524
Reputation:
Solve this in two runs:
i
, whether arrSum == i * 2
holds - equivalent to arrSum - i == i
. If it holds, you've found your searched element.In code:
int sum = 0;
for(int i : arr)
sum += i;
for(int i = 0 ; i < arr.length ; i++)
if(sum == arr[i] * 2)
return i;
return -1;
Runs in O(n)
.
Upvotes: 2