I have a very simple method that returns a tuple of integers in a list that sum to a specific target sum. The method works as expected, however, with a large list, it is slow. I have looked for articles about optimizing for loops, but I have not found anything that makes sense or helps in the case. Is there a "standard" way of optimizing for loops? Is there any way to make this particular method faster? Here is my code:
public static Tuple<int, int> FindTwoSum(IList<int> list, int sum)
{
for (int i = 0; i < list.Count; i++)
{
int needed = sum - list[i];
if (list.Contains(needed))
{
var second = list.IndexOf(needed);
if (second != i)
return new Tuple<int, int>(i, second);
}
}
return null;
}
public static void Main(string[] args)
{
Tuple<int, int> indices = FindTwoSum(new List<int>() {1, 3, 7, 5, 9 }, 10);
if (indices != null)
{
Console.WriteLine(indices.Item1 + " " + indices.Item2);
}
}