forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cs
91 lines (84 loc) · 2.79 KB
/
Solution.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
using System;
using System.Collections.Generic;
using System.Linq;
public class ThreeSumComparer : IEqualityComparer<IList<int>>
{
public bool Equals(IList<int> left, IList<int> right)
{
return left[0] == right[0] && left[1] == right[1] && left[2] == right[2];
}
public int GetHashCode(IList<int> obj)
{
return (obj[0] ^ obj[1] ^ obj[2]).GetHashCode();
}
}
public class Solution {
public IList<IList<int>> ThreeSum(int[] nums) {
Array.Sort(nums);
var results = new HashSet<IList<int>>(new ThreeSumComparer());
var cIndex = Array.BinarySearch(nums, 0);
if (cIndex < 0) cIndex = ~cIndex;
while (cIndex < nums.Length)
{
var c = nums[cIndex];
var aIndex = 0;
var bIndex = cIndex - 1;
while (aIndex < bIndex)
{
if (nums[aIndex] + nums[bIndex] + c < 0)
{
var step = 1;
while (aIndex + step < bIndex && nums[aIndex + step] + nums[bIndex] + c < 0)
{
aIndex += step;
step *= 2;
}
step /= 2;
while (step > 0)
{
if (aIndex + step < bIndex && nums[aIndex + step] + nums[bIndex] + c < 0)
{
aIndex += step;
}
step /= 2;
}
}
if (nums[aIndex] + nums[bIndex] + c > 0)
{
var step = 1;
while (aIndex < bIndex - step && nums[aIndex] + nums[bIndex - step] + c > 0)
{
bIndex -= step;
step *= 2;
}
step /= 2;
while (step > 0)
{
if (aIndex < bIndex - step && nums[aIndex] + nums[bIndex - step] + c > 0)
{
bIndex -= step;
}
step /= 2;
}
}
if (nums[aIndex] + nums[bIndex] + c == 0)
{
var list = new List<int> { nums[aIndex], nums[bIndex], c };
results.Add(list);
++aIndex;
--bIndex;
}
else if (nums[aIndex] + nums[bIndex] + c < 0)
{
++aIndex;
}
else
{
--bIndex;
}
}
++cIndex;
}
return results.ToList();
}
}