-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path3Sum.cs
35 lines (31 loc) · 1004 Bytes
/
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
public class Solution {
public IList<IList<int>> ThreeSum(int[] nums) {
var result = new List<IList<int>>();
if (nums == null || nums.Length < 3) {
return result;
}
Array.Sort(nums);
for (var i = 0; i < nums.Length - 2; i++) {
if (i != 0 && nums[i] == nums[i - 1]) {
continue;
}
var j = i + 1;
var k = nums.Length - 1;
while (j < k) {
var sum = nums[i] + nums[j] + nums[k];
if (sum == 0) {
if (k == nums.Length - 1 || nums[k] != nums[k + 1]) {
result.Add(new List<int>{nums[i], nums[j], nums[k]});
}
j++;
k--;
} else if (sum < 0) {
j++;
} else {
k--;
}
}
}
return result;
}
}