Sunday, October 12, 2014

#codingexercise
TwoSum is a method that finds the indexes of two numbers in ascending order in an array that add upto a target. Numbers are positive integers.

List<int> TwoSum(List<int> numbers, int target)
{
if (numbers.Length <= 0 || target == 0) return null;
var ret = new List<int>();
for (int i = 0; i < numbers.Length, i++)
{
  int index = numbers.IndexOf(i+1, target-numbers[i]);
  if (index != -1)
 {
   ret.Add(i);
   ret.Add(index);
 }
}
return ret;
}

No comments:

Post a Comment