forked from jianminchen/Leetcode_Julia
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path18 - 4 Sum.cs
72 lines (56 loc) · 2.27 KB
/
18 - 4 Sum.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
public class Solution
{
public IList<IList<int>> FourSum(int[] numbers, int target)
{
var quadruplets = new List<IList<int>>();
if (numbers == null || numbers.Length == 0)
{
return quadruplets;
}
Array.Sort(numbers);
var firstTwoNumbersSums = new Dictionary<int, IList<int[]>>();
var quadrupletsUnique = new HashSet<string>();
int length = numbers.Length;
for (int third = 0; third < length - 1; third++)
{
var thirdNumber = numbers[third];
for (int fourth = third + 1; fourth < length; fourth++)
{
var fourthNumber = numbers[fourth];
var lastTwoSum = thirdNumber + fourthNumber;
var search = target - lastTwoSum;
if (!firstTwoNumbersSums.ContainsKey(search))
{
continue;
}
foreach (var item in firstTwoNumbersSums[search])
{
var firstNumber = numbers[item[0]];
var secondNumber = numbers[item[1]];
var quadruplet = new int[] { firstNumber, secondNumber, thirdNumber, fourthNumber };
var key = string.Join(",", quadruplet);
if (!quadrupletsUnique.Contains(key))
{
quadrupletsUnique.Add(key);
quadruplets.Add(new List<int>(quadruplet));
}
}
}
// It is time to add visited element into two sum dictionary.
// Argue that no need to add any two indexes smaller than third, why?
for (int firstId = 0; firstId < third; firstId++)
{
var firstNumber = numbers[firstId];
var firstTwoSum = firstNumber + thirdNumber;
var newItems = new int[] { firstId, third };
if (!firstTwoNumbersSums.ContainsKey(firstTwoSum))
{
var items = new List<int[]>();
firstTwoNumbersSums.Add(firstTwoSum, items);
}
firstTwoNumbersSums[firstTwoSum].Add(newItems);
}
}
return quadruplets;
}
}