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
};

本文完,感谢阅读🌹

相关推荐
code小毛孩12 分钟前
leetcode hot100数组:缺失的第一个正数
数据结构·算法·leetcode
Warren983 小时前
Lua 脚本在 Redis 中的应用
java·前端·网络·vue.js·redis·junit·lua
mCell4 小时前
JavaScript 运行机制详解:再谈 Event Loop
前端·javascript·浏览器
legendary_bruce6 小时前
【22-决策树】
算法·决策树·机器学习
独行soc7 小时前
2025年渗透测试面试题总结-18(题目+回答)
android·python·科技·面试·职场和发展·渗透测试
艾伦~耶格尔7 小时前
【数据结构进阶】
java·开发语言·数据结构·学习·面试
帧栈8 小时前
开发避坑指南(27):Vue3中高效安全修改列表元素属性的方法
前端·vue.js
max5006008 小时前
基于桥梁三维模型的无人机检测路径规划系统设计与实现
前端·javascript·python·算法·无人机·easyui
excel8 小时前
使用函数式封装绘制科赫雪花(Koch Snowflake)
前端
愿天堂没有C++8 小时前
剑指offer第2版——面试题4:二维数组中的查找
c++·面试