-
Notifications
You must be signed in to change notification settings - Fork 1
/
findMiddle.js
41 lines (34 loc) · 868 Bytes
/
findMiddle.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
// 找到数组的中数
// 找到数组的中数
function findMiddle(numArr) {
if (numArr.length <= 1) {
return 0
}
for (let i = 0; i < numArr.length; i++) {
if (getLeftPower(numArr, i) === getRightPower(numArr, i)) {
return i
}
}
return -1;
function getLeftPower(array, index) {
if (index === 0) {
return 1;
}
let result = 1;
for (let i = 0; i < index; i++) {
result = result * array[i];
}
return result;
}
function getRightPower(array, index) {
if (index === array.length - 1) {
return 1;
}
let result = 1;
for (let i = index + 1; i < array.length; i++) {
result = result * array[i]
}
return result;
}
}
console.log(findMiddle([2,5,3,6,5,6]))