These are 2 implementations for the http://en.wikipedia.org/wiki/3SUM problem,
The first one is mine.
and in the second one I implemented Wiki's pseudo code.
Can someone please tell me if there is a difference between the two in complexity of runtime and memory space?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
//the 3SUM problem asks if a given set of n integers,
//each with absolute value bounded by some polynomial in n, contains three elements that sum to zero
public class ThreeSum
{
public ThreeSum()
{
List<int> array = new List<int> { 25, -10, -7, -3, 2, 4, 8, 10 };
List<int> res = SolveThreeSum(array);
res = SolveThreeSumWiki(array);
}
public List<int> SolveThreeSum(List<int> array)
{
for (int i = 0; i < array.Count - 2; i++ )
{
for (int j = i + 1; j < array.Count -1; j++)
{
for (int k = i + 2; k < array.Count ; k++)
{
if ((array[i] + array[j] + array[k]) == 0)
{
return new List<int> { array[i], array[j], array[k] };
}
}
}
}
return null;
}
public List<int> SolveThreeSumWiki(List<int> array)
{
array.Sort();
for (int i = 0; i < array.Count - 3; i++)
{
int a = array[0];
int start = i + 1;
int end = array.Count - 1;
while (start < end)
{
int b = array[start];
int c = array[end];
if ((a + b + c) == 0)
{
return new List<int> { a, b, c };
}
else if (a+b+c > 0)
{
end = end - 1;
}
else
{
start = start + 1;
}
}
}
return null;
}
}
}
sort
. – vnp Dec 15 '14 at 20:48