/** * @param {character[]} chars * @return {number} */// 先压缩,再返回字符串长度// 为什么不对var compress = function(chars) { let res = [] for (let i = 0; i < chars.length; i++) { res.push(chars[i]) let j = i + 1 while(chars[i] === chars[j]) { j++ } j - i > 1 && res.push(String(j - i)) i = j - 1 } return res};
/** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } *//** * @param {TreeNode} root * @return {TreeNode} */ // 本质每一层做个反转,层次遍历reversevar mirrorTree = function(root) { let q = [root] if (root === null) return null while(q.length) { for (let i = 0; i < q.length; i++) { let node = q.shift() if (node.left) q.push(node.left) if (node.right) q.push(node.right) let temp = node.left; node.left = node.right; node.right = temp; } } return root};
/** * @param {number[]} nums * @param {number} target * @return {number} */// 头尾双指针,如果发现大于,则右指针缩小var threeSumClosest = function (nums, target) { nums.sort((a, b) => a - b); let res = nums[0] + nums[1] + nums[nums.length - 1]; for (let i = 0; i < nums.length - 2; i++) { const n1 = nums[i]; let l = i + 1; let r = nums.length - 1; while (l < r) { const n2 = nums[l]; const n3 = nums[r]; const sum = n1 + n2 + n3; if (sum > target) { r--; } else { l++; } if (Math.abs(sum - target) < Math.abs(res - target)) { res = sum; } } } return res;};