-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathIntersect Array.js
50 lines (43 loc) · 1.16 KB
/
Intersect Array.js
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
// function intersectArray(arrayA, arrayB) {
// var nA = arrayA.length,
// nB = arrayB.length,
// i = 0,
// j = 0,
// intersectDict = {},
// intersection = [];
// arrayA.sort();
// arrayB.sort();
// while (i < nA && j < nB) {
// if (arrayA[i] < arrayB[j]) {
// i++;
// } else if (arrayA[i] > arrayB[j]) {
// j++;
// } else {
// if (!intersectDict[arrayA[i]]) {
// intersection.push(arrayA[i]);
// intersectDict[arrayA[i]] = true;
// }
// i++;
// j++;
// }
// }
// return intersection;
// }
function intersectArray(arrayA, arrayB) {
var nA = arrayA.length,
nB = arrayB.length,
i,
arrayADict = {},
intersectDict = {},
intersection = [];
for (i = 0; i < nA; i++) {
arrayADict[arrayA[i]] = true;
}
for (i = 0; i < nB; i++) {
if (arrayADict[arrayB[i]] && !intersectDict[arrayB[i]]) {
intersection.push(arrayB[i]);
intersectDict[arrayB[i]] = true;
}
}
return intersection;
}