-
Notifications
You must be signed in to change notification settings - Fork 11
/
1.TwoSums.cs
50 lines (46 loc) · 1.19 KB
/
1.TwoSums.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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
public class Solution
{
/*
BruteForce:
Time-Complexity : O(n^2)
Space-Complexity : O(1)
*/
public int[] TwoSum(int[] nums, int target)
{
for (int i = 0; i < nums.Length; i++)
{
for (int j = i + 1; j < nums.Length; j++)
{
if (nums[i] + nums[j] == target)
{
return new int[] { i, j };
}
}
}
throw new ArgumentException("No two elements add up to the target.");
}
/*
Optimal:
Time-Complexity : O(n)
Space-Complexity : O(n)
*/
public int[] TwoSum(int[] nums, int target)
{
//Validations
if (nums == null || nums.Length < 2)
{
return Array.Empty<int>();
}
Dictionary<int, int> numToIndexMap = new();
for (int i = 0; i < nums.Length; i++)
{
int complement = target - nums[i];
if (numToIndexMap.TryGetValue(complement, out int seen))
{
return new int[] { seen, i };
}
numToIndexMap[nums[i]] = i;
}
return Array.Empty<int>();
}
}