-
Notifications
You must be signed in to change notification settings - Fork 112
/
015-3Sum.cs
101 lines (91 loc) · 2.98 KB
/
015-3Sum.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
//-----------------------------------------------------------------------------
// Runtime: 300ms
// Memory Usage: 35.3 MB
// Link: https://leetcode.com/submissions/detail/378084324/
//-----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
namespace LeetCode
{
public class _015_3Sum
{
public IList<IList<int>> ThreeSum(int[] nums)
{
var results = new List<IList<int>>();
if (nums.Length < 3) return results;
Suffle(nums);
Quick3WaySort(nums, 0, nums.Length - 1);
if (nums[0] > 0) return results;
if (nums[nums.Length - 1] < 0) return results;
for (int i = 0; i < nums.Length - 2 && nums[i] <= 0; i++)
{
int lo = i + 1, hi = nums.Length - 1;
while (lo < hi && nums[hi] >= 0)
{
var sum = nums[i] + nums[lo] + nums[hi];
if (sum < 0)
do
lo++;
while (lo < hi && nums[lo - 1] == nums[lo]);
else if (sum > 0)
do
hi--;
while (lo < hi && nums[hi] == nums[hi + 1]);
else
{
results.Add(new List<int>() { nums[i], nums[lo], nums[hi] });
do
lo++;
while (lo < hi && nums[lo - 1] == nums[lo]);
do
hi--;
while (lo < hi && nums[hi] == nums[hi + 1]);
}
}
while (i < nums.Length - 2 && nums[i] == nums[i + 1])
i++;
}
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);
}
}
}