-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreeSum.cs
More file actions
115 lines (99 loc) · 3.32 KB
/
ThreeSum.cs
File metadata and controls
115 lines (99 loc) · 3.32 KB
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Algorithms.Problem.Arrays
{
[TestClass]
public class ThreeSum
{
public ThreeSum()
{
}
/// <summary>
/// Returns the three sum
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public List<int[]> FindThreeSumUsingHash(int[] input)
{
List<int[]> result = new List<int[]>();
HashSet<int> hashSet = new HashSet<int>();
for (int i = 0; i < input.Length - 1; i++)
{
for (int j = i + 1; j < input.Length; j++)
{
int k = - (input[i] + input[j]);
if (hashSet.Contains(k))
{
int[] result1 = new int[3];
result1[0] = input[i];
result1[1] = input[j];
result1[2] = k;
result.Add(result1);
}
else
{
hashSet.Add(input[j]);
}
}
}
return result;
}
/// <summary>
/// Make sure the input is sorted.
/// Start from first index and have two pointers = start and end.
/// Sum = arr[i] + arr[start] + arr[end] == 0 if yes, add to the list otherwise
/// Move the pointers - increment the start and decrement the end pointer.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public IList<IList<int>> FindThreeSum(int[] nums)
{
IList<IList<int>> finalResult = new List<IList<int>>();
List<int> input = new List<int>(nums);
input.Sort();
for(int i=0; i< input.Count -2; i++)
{
int j = i + 1;
int k = input.Count - 1;
while( j< k)
{
int intermediateResult = input[i] + input[j] + input[k];
// Found answer.
if (intermediateResult == 0)
{
List<int> answer = new List<int>();
answer.Add(input[i]);
answer.Add(input[j]);
answer.Add(input[k]);
finalResult.Add(answer.ToList());
j = j + 1;
k = k - 1;
}
else if (intermediateResult < 0)
{
j = j + 1;
}
else
{
k = k - 1;
}
}
}
return finalResult;
}
[TestMethod]
public void TestFindingThreeSum()
{
// int[] input = { -1, 0, 1, 2, -1 ,-4};
// result = {-1, -1, 2}
// {-1, 0, 1}
int[] expectedResult = { 0, -1, 1};
int[] input = { -1, 0, 1, 2, -1, -4 };// { 0 , -1, 2, -3, 1};
IList<IList<int>> result = this.FindThreeSum(input);
}
}
}