1. 有效括号匹配
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
const isValid = function (s) { if (s.length % 2 === 1) return false; let stack = []; const type = new Map([ [')', '('], ['}', '{'], [']', '['] ]); for (let char of s) { if (type.has(char)) { if (stack.length === 0 || stack[stack.length - 1] !== type.get(char)) { return false; } stack.pop(); } else { stack.push(char); } } return stack.length === 0; };
|
2. 给你一棵二叉树,想象你站在他的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值,示例:输入:[1,2,3,null,5,null,4],输出:[1,3,4]
二叉树数组表示的映射关系是这样的:
所以示例的二叉线表示出来是:

下面看查看右侧视图的代码实现吧
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
|
const rightSideView = (input) => { function TreeNode(val, left = null, right = null) { this.val = val; this.left = left; this.right = right; } function BFS(_root){ if (!root) return [];
const queue = [root]; const result = [];
while (queue.length > 0) { const levelSize = queue.length;
for (let i = 0; i < levelSize; i++) { const node = queue.shift();
if (i === levelSize - 1) { result.push(node.val); }
if (node.left) queue.push(node.left); if (node.right) queue.push(node.right); } } return result; } const root = new TreeNode(1); root.left = new TreeNode(2); root.right = new TreeNode(3); root.left.right = new TreeNode(5); root.right.right = new TreeNode(4); return BFS(root); }
|
3 给指定的 key 属性给数组对象去重
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
|
function uniqueArr(arr,key){ return arr.filter((item, index, self) => index === self.findIndex(t => t[key] === item[key])); }
function uniqueArr2(arr=[],key){ return Array.from(new Map(arr.map(item=>[item[key],item])).values()); }
function uniqueArr3(arr=[],key){ return arr.reduce((prev,cur)=>{ const x = prev.find(item => item[key] === cur[key]); if(!x){ prev.push(cur); } return prev; },[]); }
|