-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTwo Sum (O^N) Solution.cs
26 lines (23 loc) · 1 KB
/
Two Sum (O^N) Solution.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class Solution {
public int[] TwoSum(int[] nums, int target) {
int[] solution = new int[2];
//O(N) solution
Dictionary<int, int> seenInts = new Dictionary<int, int>();// Key = value of num, value = index of array
for(int i = 0; i < nums.Length; i++) //Scan through all nums
{
int hypotheticalComplementary = target - nums[i]; //Compute hypothetical Complementary
if (seenInts.ContainsKey(hypotheticalComplementary)) //If we've seen that complementary value already, we've found a solution
{
solution[0] = seenInts[hypotheticalComplementary];
solution[1] = i;
break;
}
else
{
if (!seenInts.ContainsKey(nums[i])) //If we've already seen a number and have it added to our dict, ignore it.
seenInts.Add(nums[i], i);
}
}
return solution;
}
}