-
Notifications
You must be signed in to change notification settings - Fork 120
/
Copy path018-4Sum.cs
112 lines (100 loc) · 3.47 KB
/
018-4Sum.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
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
//-----------------------------------------------------------------------------
// Runtime: 532ms
// Memory Usage:
// Link:
//-----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
namespace LeetCode
{
public class _018_4Sum
{
public IList<IList<int>> FourSum(int[] nums, int target)
{
var results = new List<IList<int>>();
if (nums.Length < 4) { return results; }
Suffle(nums);
Quick3WaySort(nums, 0, nums.Length - 1);
var cache = new Dictionary<int, IList<int>>();
int temp, index1, index2;
for (index1 = 0; index1 < nums.Length - 1; index1++)
{
for (index2 = index1 + 1; index2 < nums.Length; index2++)
{
temp = nums[index1] + nums[index2];
if (!cache.ContainsKey(temp))
{
cache[temp] = new List<int>();
}
cache[temp].Add(index1);
cache[temp].Add(index2);
}
}
IList<int> list1, list2;
foreach (var pair in cache)
{
if (!cache.TryGetValue(target - pair.Key, out list2)) { continue; }
list1 = pair.Value;
for (index1 = 0; index1 < list1.Count; index1 += 2)
{
for (index2 = 0; index2 < list2.Count; index2 += 2)
{
if ((list1[index1 + 1] < list2[index2]) && (list1[index1] != list2[index2] && list1[index1] != list2[index2 + 1]))
{
results.Add(new List<int>() { nums[list1[index1]], nums[list1[index1 + 1]], nums[list2[index2]], nums[list2[index2 + 1]] });
while (index2 + 2 < list2.Count && nums[list2[index2 + 2]] == nums[list2[index2]])
{
index2 += 2;
}
}
}
while (index1 + 2 < list1.Count && nums[list1[index1 + 3]] == nums[list1[index1 + 1]])
{
index1 += 2;
}
}
}
return results;
}
void Suffle(int[] nums)
{
var random = new Random();
int N = nums.Length;
int r, temp;
for (int i = 0; i < N; i++)
{
r = random.Next(i + 1);
temp = nums[r];
nums[r] = nums[i];
nums[i] = temp;
}
}
void Quick3WaySort(int[] nums, int lo, int hi)
{
if (lo >= hi) { return; }
var lt = lo;
var gt = hi;
var i = lo;
var v = nums[i];
int temp;
while (i <= gt)
{
if (nums[i] > v)
{
temp = nums[i];
nums[i] = nums[gt];
nums[gt--] = temp;
}
else if (nums[i] < v)
{
temp = nums[i];
nums[i] = nums[lt];
nums[lt++] = temp;
}
else { i++; }
}
Quick3WaySort(nums, lo, lt - 1);
Quick3WaySort(nums, gt + 1, hi);
}
}
}