443. 压缩字符串

  1. /**
  2. * @param {character[]} chars
  3. * @return {number}
  4. */
  5. // 先压缩,再返回字符串长度
  6. // 为什么不对
  7. var compress = function(chars) {
  8. let res = []
  9. for (let i = 0; i < chars.length; i++) {
  10. res.push(chars[i])
  11. let j = i + 1
  12. while(chars[i] === chars[j]) {
  13. j++
  14. }
  15. j - i > 1 && res.push(String(j - i))
  16. i = j - 1
  17. }
  18. return res
  19. };

剑指 Offer 27. 二叉树的镜像

  1. /**
  2. * Definition for a binary tree node.
  3. * function TreeNode(val) {
  4. * this.val = val;
  5. * this.left = this.right = null;
  6. * }
  7. */
  8. /**
  9. * @param {TreeNode} root
  10. * @return {TreeNode}
  11. */
  12. // 本质每一层做个反转,层次遍历reverse
  13. var mirrorTree = function(root) {
  14. let q = [root]
  15. if (root === null) return null
  16. while(q.length) {
  17. for (let i = 0; i < q.length; i++) {
  18. let node = q.shift()
  19. if (node.left) q.push(node.left)
  20. if (node.right) q.push(node.right)
  21. let temp = node.left;
  22. node.left = node.right;
  23. node.right = temp;
  24. }
  25. }
  26. return root
  27. };

1312. 让字符串成为回文串的最少插入次数

16. 最接近的三数之和

  1. /**
  2. * @param {number[]} nums
  3. * @param {number} target
  4. * @return {number}
  5. */
  6. // 头尾双指针,如果发现大于,则右指针缩小
  7. var threeSumClosest = function (nums, target) {
  8. nums.sort((a, b) => a - b);
  9. let res = nums[0] + nums[1] + nums[nums.length - 1];
  10. for (let i = 0; i < nums.length - 2; i++) {
  11. const n1 = nums[i];
  12. let l = i + 1;
  13. let r = nums.length - 1;
  14. while (l < r) {
  15. const n2 = nums[l];
  16. const n3 = nums[r];
  17. const sum = n1 + n2 + n3;
  18. if (sum > target) {
  19. r--;
  20. } else {
  21. l++;
  22. }
  23. if (Math.abs(sum - target) < Math.abs(res - target)) {
  24. res = sum;
  25. }
  26. }
  27. }
  28. return res;
  29. };