-
Notifications
You must be signed in to change notification settings - Fork 151
/
Copy pathEx_1_4_08.java
46 lines (40 loc) · 985 Bytes
/
Ex_1_4_08.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
package Ch_1_4;
import edu.princeton.cs.algs4.StdOut;
import java.util.Arrays;
/**
* Created by HuGuodong on 2019/8/14.
*/
public class Ex_1_4_08 {
public static int countTwoEqualsSlow(int[] a) {
int cnt = 0;
int N = a.length;
for (int i = 0; i < N; i++)
for (int j = i + 1; j < N; j++)
if (a[i] == a[j])
cnt++;
return cnt;
}
public static int countTwoEqualsFast(int[] a) {
int N = a.length;
int count = 0;
Arrays.sort(a);
int dup = 0;
for (int i = 1; i < N; i++) {
if (a[i - 1] == a[i]) {
dup++;
} else {
count += dup * (dup + 1) / 2;
dup = 0;
}
if (i == N - 1) {
count += dup * (dup + 1) / 2;
}
}
return count;
}
public static void main(String[] args) {
int[] a = {4, 1, 1, 1, 1, 2, 2, 3, 3, 3, 4};
StdOut.printf("slow count : %d\n", countTwoEqualsSlow(a));
StdOut.printf("fast count : %d\n", countTwoEqualsFast(a));
}
}