-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathZeroSumTriplets.cs
More file actions
77 lines (66 loc) · 2.09 KB
/
ZeroSumTriplets.cs
File metadata and controls
77 lines (66 loc) · 2.09 KB
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
using System;
namespace DA.Algorithms.Problems
{
public static class ZeroSumTriplets
{
/// <summary>
/// Find a triplet whose sum is zero.
/// <para>Time Complexity - O(n^3)</para>
/// </summary>
public static bool BruteForce (int[] array)
{
for (int i = 0; i < array.Length - 2; i++)
for (int j = i + 1; j < array.Length - 1; j++)
for (int k = j + 1; k < array.Length; k++)
if (array[i] + array[j] + array[k] == 0)
return true;
return false;
}
/// <summary>
/// Find a triplet whose sum is zero.
/// <para>Time Complexity - O(n^2)</para>
/// </summary>
public static bool UseSorting (int[] array)
{
int start, stop, currentSum;
Array.Sort (array);
for (int i = 0; i < array.Length - 2; i++)
{
start = i + 1;
stop = array.Length - 1;
while (start < stop)
{
currentSum = array[i] + array[start] + array[stop];
if (currentSum == 0) return true;
else if (currentSum > 0) --stop;
else ++start;
}
}
return false;
}
public static void SmallerThanValue (int[] array, int value)
{
int start, stop;
int count = 0;
Array.Sort (array);
for (int i = 0; i < array.Length - 2; i++)
{
start = i + 1;
stop = array.Length - 1;
while (start < stop)
{
if (array[i] + array[start] + array[stop] >= value)
{
--stop;
}
else
{
count += stop - start;
++start;
}
}
}
Console.WriteLine (count);
}
}
}