# 斐波那契数列
# 复习->合并二维有序数组为一维数组
// flat Infinity
function a1(arr) {
return arr.flat(Infinity).sort((a, b) => a - b);
}
// reduce
function a2(arr) {
return arr.reduce((acc, cur) => {
return Array.isArray(cur) ? [...acc, a2(cur)] : [...acc, cur];
}, []);
}
// concat
function a3(arr) {
let copyArr = [...arr];
while (copyArr.some((item) => Array.isArray(item))) {
copyArr = [].concat([...copyArr]);
}
return copyArr;
}
// 归并排序
function a4(arr) {
function mergeSort(arr) {
if (arr.length < 2) {
return arr;
}
const middleIndex = arr >> 1;
const left = arr.slice(0, middleIndex);
const right = arr.slice(middleIndex);
return merge(mergeSort(left), mergeSort(right));
}
function merge(left, right) {
const result = [];
while (left.length && right.length) {
if (left[0] < right[0]) {
result.push(left.shift());
} else {
result.push(right.shift());
}
}
while (left.length) {
result.push(left.shift());
}
while (right.length) {
result.push(right.shift());
}
return result;
}
function flatten(arr) {
return arr.reduce((pre, cur) => {
return pre.concat(Array.isArray(cur) ? flatten(cur) : cur);
}, []);
}
return mergeSort(flatten(soucreArr));
}
# 斐波那契 (1,1,2,3,5,8,13,21,34.。。)
function fibonacci01(n, map = {}) {
console.log(n);
if (n === 1 || n === 2) return 1;
if (map[n]) return map[n];
const data = fibonacci01(n - 1, map) + fibonacci01(n - 2, map);
map[n] = data;
return data;
}
function fibonacci02(n, v1 = 1, v2 = 1) {
if (n === 1) return v1;
if (n === 2) return v2;
return fibonacci02(n - 1, v2, v1 + v21);
}
function fibonacci03(n) {
let pre = 1;
let cur = 1;
let data;
if (n == 1 || n == 2) return 1;
for (let i = 3; i <= n; i++) {
data = pre + cur;
pre = cur;
cur = data;
}
return data;
}