Skip to content

Commit dc2ec6e

Browse files
committed
https://leetcode.com/problems/two-sum/
1 parent 04beec1 commit dc2ec6e

File tree

2 files changed

+45
-2
lines changed

2 files changed

+45
-2
lines changed

LeetCodeSolutions/HashMap/TwoSum.cs

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
namespace LeetCodeSolutions.HashMap;
2+
3+
public class TwoSumSolution
4+
{
5+
public int[] TwoSum(int[] nums, int target)
6+
{
7+
Dictionary<int, int> seen = new Dictionary<int, int>();
8+
int[] result = new int[2];
9+
for (int i = 0; i < nums.Length; i++)
10+
{
11+
int diff = target - nums[i];
12+
if (seen.ContainsKey(diff))
13+
{
14+
result[0] = seen[diff];
15+
result[1] = i;
16+
return result;
17+
}
18+
else if (!seen.ContainsKey(nums[i]))
19+
seen.Add(nums[i], i);
20+
}
21+
22+
return result;
23+
}
24+
25+
[Test(Description = "https://leetcode.com/problems/two-sum/")]
26+
[Category("Easy")]
27+
[Category("LeetCode")]
28+
[Category("Two Sum")]
29+
[TestCaseSource(nameof(Input))]
30+
[Category("HashMap")]
31+
[Category("TopInterview")]
32+
public void Test1((int[] Output, (int[] nums, int target) Input) item)
33+
{
34+
var response = TwoSum(item.Input.nums, item.Input.target);
35+
Assert.That(response, Is.EqualTo(item.Output));
36+
}
37+
38+
public static IEnumerable<(int[] Output, (int[] nums, int target) Input)> Input =>
39+
new List<(int[] Output, (int[] nums, int target) Input)>()
40+
{
41+
([0, 1], ([2, 7, 11, 15], 9)),
42+
};
43+
}

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
![](https://img.shields.io/badge/Neovim-57A143.svg?logo=Neovim&amp;logoColor=white)
44
![](https://img.shields.io/badge/Visual_Studio_Code-0078D4?logo=visual%20studio%20code&amp;logoColor=white)
5-
![](https://img.shields.io/badge/Progress-27%2F150-0078D4)
5+
![](https://img.shields.io/badge/Progress-28%2F150-0078D4)
66

77
This repository contains solutions to the Leetcode Top Interview 150 problems.
88

@@ -91,7 +91,7 @@ The Top Interview 150 collection on Leetcode is a curated set of 150 interview q
9191
| 41 | Word Pattern | Easy | |
9292
| 42 | Valid Anagram | Easy ||
9393
| 43 | Group Anagrams | Medium | |
94-
| 44 | Two Sum | Easy | |
94+
| 44 | Two Sum | Easy | |
9595
| 45 | Happy Number | Easy | |
9696
| 46 | Contains Duplicate II | Easy ||
9797
| 47 | Longest Consecutive Sequence | Medium | |

0 commit comments

Comments
 (0)