Skip to content

Commit c6ecdd4

Browse files
committed
https://leetcode.com/problems/3sum/
1 parent 1351bdc commit c6ecdd4

File tree

2 files changed

+69
-1
lines changed

2 files changed

+69
-1
lines changed
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
namespace LeetCodeSolutions.TwoPointers
2+
{
3+
public class ThreeSumSolution
4+
{
5+
public IList<IList<int>> ThreeSum(int[] nums)
6+
{
7+
IList<IList<int>> returnValue = new List<IList<int>>();
8+
Array.Sort(nums);
9+
10+
for (int i = 0; i < nums.Length; i++)
11+
{
12+
if (i > 0 && nums[i] == nums[i - 1])
13+
continue;
14+
15+
int left = i + 1;
16+
int right = nums.Length - 1;
17+
18+
while (left < right)
19+
{
20+
int threeSum = nums[i] + nums[left] + nums[right];
21+
22+
if (threeSum > 0)
23+
right--;
24+
else if (threeSum < 0)
25+
left++;
26+
else
27+
{
28+
List<int> currentList =
29+
[
30+
nums[i],
31+
nums[left],
32+
nums[right]
33+
];
34+
returnValue.Add(currentList);
35+
left++;
36+
while (nums[left] == nums[left - 1] && left < right)
37+
left++;
38+
}
39+
}
40+
}
41+
42+
return returnValue;
43+
}
44+
45+
[Test(Description = "https://leetcode.com/problems/3sum/")]
46+
[Category("Medium")]
47+
[Category("LeetCode")]
48+
[Category("3Sum")]
49+
[TestCaseSource(nameof(Input))]
50+
[Category("TwoPointers")]
51+
[Category("TopInterview")]
52+
public void Test1((IList<IList<int>> Output, int[] Input) item)
53+
{
54+
var response = ThreeSum(item.Input);
55+
Assert.That(response, Is.EqualTo(item.Output));
56+
}
57+
58+
public static IEnumerable<(IList<IList<int>> Output, int[] Input)> Input =>
59+
new List<(IList<IList<int>> Output, int[] Input)>()
60+
{
61+
(new List<IList<int>>()
62+
{
63+
new List<int>() { -1, -1, 2 },
64+
new List<int>() { -1, 0, 1 }
65+
}, [-1, 0, 1, 2, -1, -4]),
66+
};
67+
}
68+
}

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ The Top Interview 150 collection on Leetcode is a curated set of 150 interview q
7373
| 26 | Is Subsequence | Easy ||
7474
| 27 | Two Sum II - Input Array Is Sorted | Medium ||
7575
| 28 | Container With Most Water | Medium ||
76-
| 29 | 3Sum | Medium | |
76+
| 29 | 3Sum | Medium | |
7777
| <br> Sliding Window<br> | | | |
7878
| 30 | Minimum Size Subarray Sum | Medium | |
7979
| 31 | Longest Substring Without Repeating Characters | Medium | |

0 commit comments

Comments
 (0)