30 天刷题挑战(十二)

题目来源: LeetCode 75 30 天 JavaScript 挑战

2727. 判断对象是否为空

思路

判断 obj 是否为数组

代码

ts 复制代码
// 普通写法
function isEmpty(obj: Obj): boolean {
  if (Array.isArray(obj)) {
    return obj.length === 0
  }

  return Object.keys(obj).length === 0
};

// O(1) 写法
function isEmpty(obj: Obj): boolean {
  for (let key in obj) return false;
  return true;
};

2677. 分块数组

思路

使用数组 splice 方法分割数组

代码

ts 复制代码
function chunk(arr: Obj[], size: number): Obj[][] {
  if (!arr.length) {
    return []
  }

  const res = []
   
  while (arr.length) {
    let _chunk = arr.splice(0, size)
    res.push(_chunk)
  }
   
  return res
};

2619. 数组原型对象的最后一个元素

代码

ts 复制代码
Array.prototype.last = function() {
  const len = this.length
  if (!len) {
    return -1
  }
  return this[len - 1]
};

206. 反转链表

思路

递归法,先递归遍历链表到尾部,回溯的时候修改节点 next 指向

代码

ts 复制代码
function reverseList(head: ListNode | null): ListNode | null {
  return recur(head, null)
};

function recur(cur: ListNode | null, pre: ListNode) {
  if (cur === null) {
    return pre
  }
  // 递归
  let res = recur(cur.next, cur)
  // 回溯
  cur.next = pre
  return res // 返回未节点
}

2130. 链表最大孪生和

思路

  1. 使用快慢指针找到中间节点
  2. 翻转后半部分
  3. 同时遍历两部分,节点值相加得到最大结果

代码

ts 复制代码
function pairSum(head: ListNode | null): number {
   let fast = head
   let slow = head
   let prev = null

   while(fast !== null && fast.next !== null) {
     let next = slow.next
     fast = fast.next.next
     
     slow.next = prev
     prev = slow
     slow = next
   }

   let max = 0

   while(slow !== null) {
     max = Math.max(max, prev.val + slow.val)
     prev = prev.next
     slow = slow.next
   }

  return max
};

104. 二叉树的最大深度

思路

递归法,分别求左右子树高度,最后取大值加一。

代码

ts 复制代码
function maxDepth(root: TreeNode | null): number {
  if (root === null) {
    return 0
  }

  let leftDepth = maxDepth(root.left)
  let rightDepth = maxDepth(root.right)
   
  return Math.max(leftDepth, rightDepth) + 1
};

本文完,感谢阅读🌹

相关推荐
Cosolar7 小时前
AutoGen 精通教程:从零到企业级多 Agent 系统架构师
人工智能·后端·面试
Hi~晴天大圣7 小时前
npm使用介绍
前端·npm·node.js
888CC++8 小时前
如何在 C 语言中进行程序调试?
前端·javascript·算法
喵个咪8 小时前
基于 Taro 的 Headless CMS 多端前端架构:技术解析与二次开发导引
前端·react.js·taro
狂炫冰美式8 小时前
你还在古法PPT吗,试试HTML呢?免费编辑导出工具给 xdm 放这了
前端·后端·github
万少9 小时前
未来组织的分水岭不是员工数量,而是人才密度
前端·后端·面试
任磊abc9 小时前
nextjs16配置eslint+prettier
前端·eslint·nextjs·prettier
x***r1519 小时前
Another-Redis-Desktop-Manager.1.3.7安装步骤详解(附Redis可视化连接与Key管理教程)
前端·bootstrap·html
Captaincc9 小时前
你真的知道自己把 AI 用在了哪里吗?这是 Vibe Usage 想回答的问题
前端·vibecoding