-
Notifications
You must be signed in to change notification settings - Fork 0
/
arrayHasIntersections.py
94 lines (64 loc) · 1.71 KB
/
arrayHasIntersections.py
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import TestHelper
from datetime import datetime
def IsArraysIntersected(arr1, arr2):
for i in arr1:
for j in arr2:
if i == j:
return True
return False
def IntersectionCount(arr1, arr2):
count = 0
for i in arr1:
for j in arr2:
if i == j:
count += 1
return count
def IntersectionCountSorted(arr1, arr2):
count = 0
arr1.sort()
arr2.sort()
index1 = 0
index2 = 0
n = len(arr1)
m = len(arr2)
while index1 < n and index2 < m:
e1 = arr1[index1]
e2 = arr2[index2]
if e1 == e2:
count += 1
index2 += 1
while e1 < e2 and index1 < n:
index1 += 1
if index1 < n:
e1 = arr1[index1]
while e2 < e1 and index2 < m:
index2 += 1
if index2 < m:
e2 = arr2[index2]
return count
def IntersectionCountHash(arr1, arr2):
count = 0
d1 = {}
for i in arr1:
d1[i] = 1
for j in arr2:
if j in d1:
count += 1
return count
a1 = TestHelper.GenerateRandomIntListWithoutDuplicates(50000, 0, 1000000)
a2 = TestHelper.GenerateRandomIntListWithoutDuplicates(40000, 0, 1000000)
print("solution 1")
t1 = datetime.now()
count = IntersectionCount(a1, a2)
t2 = datetime.now()
print("IntersectionCount", count, "Time diff", t2-t1)
print("solution 2")
t1 = datetime.now()
count = IntersectionCountSorted(a1, a2)
t2 = datetime.now()
print("IntersectionCountSorted", count, "Time diff", t2-t1)
print("solution 3")
t1 = datetime.now()
count = IntersectionCountHash(a1, a2)
t2 = datetime.now()
print("IntersectionCountHash", count, "Time diff", t2-t1)