-
Notifications
You must be signed in to change notification settings - Fork 344
/
有序数组求交集.js
79 lines (63 loc) · 1.24 KB
/
有序数组求交集.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
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
let a = []
for (let index = 0; index < 500; index++) {
a.push(i)
}
for (let i = 16; i < 10000; i++) {
a.push(i)
}
let b = []
for (let index = 0; index < 500; index++) {
b.push(i)
}
for (let i = 10001; i < 50000; i++) {
b.push(i)
}
function mapIntersection(arr1, arr2) {
console.time()
let map = new Map()
for (let i = 0; i < arr1.length; i++) {
map.set(arr1[i], true)
}
let result = []
for (let i = 0; i < arr2.length; i++) {
let val = arr2[i]
if (map.get(val)) {
result.push(val)
}
}
console.timeEnd()
return result
}
console.log("mapIntersection", mapIntersection(a, b))
function pointIntersection(arr1, arr2) {
console.time()
let i = 0
let j = 0
let l1 = arr1.length
let l2 = arr2.length
let result = []
while (i < l1 && j < l2) {
let val1 = arr1[i]
let val2 = arr2[j]
let val1Last = arr1[i - 1]
let val2Last = arr2[j - 1]
if (val1 > val2) {
i++
}
if (val1 === val2) {
result.push(val1)
i++
j++
}
if (val1 < val2) {
j++
}
if (val1 > val2Last || val2 > val1Last) {
console.timeEnd()
return result
}
}
console.timeEnd()
return result
}
console.log('pointIntersection', pointIntersection(a, b))