-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathThreeSum.java
51 lines (48 loc) · 1.37 KB
/
ThreeSum.java
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
/* *****************************************************************************
* Name: Alan Turing
* NetID: aturing
* Precept: P00
*
* Description: Prints 'Hello, World' to the terminal window.
* By tradition, this is everyone's first program.
* Prof. Brian Kernighan initiated this tradition in 1974.
*
**************************************************************************** */
import edu.princeton.cs.algs4.In;
import edu.princeton.cs.algs4.StdOut;
public class ThreeSum {
public static int binarySearch(int[] a, int key)
{
int lo = 0;
int hi = a.length;
while(lo <= hi)
{
int mid = lo + (hi - lo) / 2;
if (key < a[mid]) hi = mid - 1;
else if (key > a[mid]) lo = mid + 1;
else return mid;
}
return -1;
}
public static int count(int[] a)
{
int N = a.length;
int count = 0;
for (int i = 0; i < N; i++)
{
for (int j = i + 1; j < N; j++)
{
int ret = binarySearch(a, -(a[i] + a[j]));
if (ret != -1)
{
count += 1;
}
}
}
return count;
}
public static void main(String[] args) {
int [] a = In.readInts(args[0]);
StdOut.println(count(a));
}
}