-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreeSumModified.java
More file actions
40 lines (31 loc) · 933 Bytes
/
ThreeSumModified.java
File metadata and controls
40 lines (31 loc) · 933 Bytes
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
import edu.princeton.cs.algs4.In;
import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.Stopwatch;
import java.util.*;
public class ThreeSumModified{
public static int count(int[] a){
int n=a.length;
int cnt=0;
Arrays.sort(a);
for (int i=0;i<n-2;i++){
int j=i+1;
int k=n-1;
while(j<k){
int sum = a[i] + a[j] + a[k];
if ( sum < 0)
j++;
if ( sum >= 0)
k--;
if (sum==0) cnt++;
}
}
return cnt;
}
public static void main(String[] args){
int a[] = In.readInts(args[0]);
Stopwatch stopwatch = new Stopwatch();
StdOut.println(ThreeSum.count(a));
double time = stopwatch.elapsedTime();
StdOut.println("elapsed time is: "+time);
}
}