Created
October 11, 2017 03:29
-
-
Save polunzh/426ed2938fbb0eb719e03f1103b98eb0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict' | |
/** | |
* 该函数将传入的数组整理成 [小于等于v的数],v,[大于v的数], v为数组的第一个数; | |
* 如果传入的不是数组,则会抛出异常 | |
* | |
* @param {any} array | |
* @returns | |
*/ | |
function part(array) { | |
if (!Array.isArray(array)) { | |
throw new Error('array: must be Array'); | |
} | |
if (array.length <= 1) return array; | |
const val = array[0]; | |
/* | |
分别在第一个和第二个索引位置插入两个空数组 | |
构建数据结构: [小于等于v的数],v,[大于v的数] | |
*/ | |
array.unshift([]); | |
array.splice(2, 0, []); | |
const len = array.length; | |
for (let i = len - 1; i > 2; i--) { | |
if (array[i] <= val) array[0].push(array[i]); | |
else array[2].push(array[i]); | |
array.length--; // 将数组最右侧已经插入过的数据删除 | |
} | |
// 如果第一个和最后一个数组为空,则删除 | |
if (array[0].length === 0) array.splice(0, 1); | |
if (array[array.length - 1].length === 0) array.splice(2, 1); | |
} | |
const arr = [1, 2]; | |
const arr1 = [1]; | |
const arr2 = [10, 10, 10, 10, 10, 10, 10, 10, -1, -1, 100]; | |
// const arr3 = [2, 1, 0]; | |
const arr3 = [-1, 1, 0]; | |
// const arr3 = [10, 10, 10, 2, 1, 100, 20, 10, 10, 2, 200]; | |
const s = Date.now(); | |
// part(arr); | |
// for (let i = 0; i < 10000000; i++) { | |
// const arr3 = [10, 10, 10, 2, 1, 100, 20, 10, 10, 2, 200]; | |
// part(arr3); | |
// // arr3.sort(); | |
// } | |
// console.log(arr1); | |
// arr2arr.sort(); | |
part(arr); | |
console.log(Date.now() - s); | |
console.log(arr); | |
// console.log(arr3); | |
// console.log(part([4, 12, 21, 3, 1, 3, 4, 1, 4, 5])); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict' | |
/** | |
* 计算二叉树中所有v节点的值的和 | |
* | |
* @param {any} n | |
* @returns 二叉树中所有v节点的值的和 | |
*/ | |
function sum(n) { | |
let res = 0; // 在每一层递归调用中使用一个临时变量保存当前层的值 | |
for (let k in n) { | |
if (n.hasOwnProperty(k)) { | |
if (typeof n[k] === 'object') { // 如果是对象,则递归遍历 | |
res += sum(n[k]); | |
} else if (k === 'v' && typeof n[k] === 'number') { // 如果是结点'v',则将值保存到临时变量 | |
res += n[k]; | |
} | |
} | |
} | |
return res; // 返回当前层的值到上一层 | |
} | |
const s = sum({ | |
l: { | |
v: 1, | |
s: { | |
i: null, | |
v: 10 | |
} | |
}, | |
a: { | |
c: 2, | |
d: 1 | |
}, | |
c: { | |
d: 'jfiewf', | |
v: 'jdjfwe' | |
} | |
}); | |
console.log(s); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment