Most C# developers will place opening braces on a new line. If you do this as well then you make it easier to read the code by others.
complementandindexshould usevartype"type" as welltwoSumSolutionisn't really needed and is only adding noise to the code.I like to use
if (bool == false)instead ofif (!bool)because I can grasp it at first glance without wondering wether I see a exclamation sign or not.Instead of using the
Count()extension method I prefer using theLengthproperty for arrays. UsingCount()will envolve a soft cast toICollection<T>and anullcheck which just isn't needed.checking if
complement > 0will remove unneeded calls toTryGetValue(), but has implications on certain inputs liketarget = 0and an array[-3, 7, 3].
Implementing the mentioned points will lead to
public int[] TwoSum(int[] nums, int target)
{
var numsDictionary = new Dictionary<int, int>();
var complement = 0;
for (var i = 0; i < nums.Length; i++)
{
complement = target - nums[i];
var index = 0;
if (complement > 0 && numsDictionary.TryGetValue(complement, out index))
{
return new int[] { index, i };
}
if (numsDictionary.ContainsKey(nums[i]) == false)
{
numsDictionary.Add(nums[i], i);
}
}
return null;
}