leetCode
二叉树
二叉树的直径
var diameterOfBinaryTree = function(root) {
let maxDiameter = 0;
const traverse = (root) => {
if(!root) return 0 ;
let leftMax = traverse(root.left);
let rightMax = traverse(root.right);
maxDiameter = Math.max(maxDiameter, leftMax + rightMax);
return 1 + Math.max(leftMax, rightMax);
}
traverse(root);
return maxDiameter
};
二叉树层序遍历
var levelOrder = function(root) {
let res = [];
if(!root) return res;
let q = [];
q.push(root);
while(q.length > 0){
let size = q.length;
let sub = [];
while(size > 0){
let curr = q.shift();
sub.push(curr.val);
if(curr.left) q.push(curr.left);
if(curr.right) q.push(curr.right);
size--;
}
res.push(sub);
}
return res;
};
var levelOrder = function(root) {
const result = [];
const traverse = (node, depth) => {
if(!node) return;
if(!result[depth]){
result[depth] = [];
}
result[depth].push(node.val);
traverse(node.left, depth + 1);
traverse(node.right, depth + 1);
}
traverse(root, 0);
return result;
};
排序算法
1、冒泡排序
function bubbleSort(arr) {
const result = [...arr];
const n = result.length;
for (let i = 0; i < n - 1; i++) {
for (let j = 0; j < n - 1 - i; j++) {
if (result[j] > result[j + 1]) {
[result[j], result[j + 1]] = [result[j + 1], result[j]];
}
}
}
return result;
}
console.log(bubbleSort([3, 1, 6, 2, 8]));
2、快速排序
function quickSort(arr) {
if (arr.length <= 1) return arr;
const pivotIndex = Math.floor(arr.length / 2);
const pivot = arr[pivotIndex];
const left = [];
const middle = [];
const right = [];
for (let i = 0; i < arr.length; i++) {
if (arr[i] < pivot) {
left.push(arr[i]);
} else if (arr[i] === pivot) {
middle.push(arr[i]);
} else {
right.push(arr[i]);
}
}
return [...quickSort(left), ...middle, ...quickSort(right)];
}turn [...quickSort(left), ...middle, ...quickSort(right)];
}
非leetcode
1、输出出现次数最多的字母的前缀数之和
function fn(str) {
const charCount = {};
for (let i = 0; i < str.length; i++) {
const char = str[i].toLowerCase();
if (!charCount[char]) {
charCount[char] = [];
}
charCount[char].push(i);
}
let maxChar = '';
let maxCount = 0;
for (const [char, positions] of Object.entries(charCount)) {
if (positions.length > maxCount) {
maxCount = positions.length;
maxChar = char;
}
}
const sum = charCount[maxChar].reduce((a, b) => a + b, 0);
return {
maxChar,
sum,
};
}
console.log(fn('patchRoutes'));
2、react手写一个十分秒的倒计时
import React, { useState, useEffect } from 'react';
function CountDown({ initialTime = 3600 }) {
const [timeLeft, setTimeLeft] = useState(initialTime);
const formatTime = (seconds) => {
const hours = Math.floor(seconds / 3600);
const minutes = Math.floor((seconds % 3600) / 60);
const secs = seconds % 60;
return {
hours: hours.toString().padStart(2, '0'),
minutes: minutes.toString().padStart(2, '0'),
seconds: secs.toString().padStart(2, '0'),
};
};
const { hours, minutes, seconds } = formatTime(timeLeft);
useEffect(() => {
let timer = setInterval(() => {
setTimeLeft((prev) => {
if (prev <= 1) {
console.log('倒计时结束');
return 0;
}
return prev - 1;
});
}, 1000);
return () => clearInterval(timer);
}, []);
return (
<div>
<div>时:{hours}</div>
<div>分:{minutes}</div>
<div>秒:{seconds}</div>
</div>
);
}
export default CountDown;
3、使用js实现一个栈
class Stack {
constructor() {
this.items = [];
}
push(element) {
this.items.push(element);
}
pop() {
if (this.isEmpty()) {
return undefined;
}
return this.items.pop();
}
peek() {
if (this.isEmpty()) {
return undefined;
}
return this.items[this.items.length - 1];
}
isEmpty() {
return this.items.length === 0;
}
size() {
return this.items.length;
}
}
const stack = new Stack();
console.log(stack.isEmpty());
console.log(stack.size());
stack.push(1);
stack.push(2);
stack.push(3);
console.log(stack.size());
console.log(stack.peek());
console.log(stack.isEmpty());
console.log(stack.pop());
console.log(stack.pop());
console.log(stack.size());
console.log(stack.peek());
console.log(stack.pop());
console.log(stack.isEmpty());
console.log(stack.pop());
4、获取嵌套对象属性
function deepGet(obj, path, defaultValue = undefined) {
if (!obj || typeof obj !== 'object') return defaultValue;
if (!path || typeof path !== 'string') return defaultValue;
const keys = path.split('.');
let result = obj;
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
if (result === null || result === undefined || typeof result !== 'object') {
return defaultValue;
}
result = result[key];
}
return result === undefined ? defaultValue : result;
}
const obj = {
a: {
b: {
c: 1,
d: null,
e: 0,
f: false,
},
},
};
console.log(deepGet(obj, 'a.b.c'));
console.log(deepGet(obj, 'a.b.d'));
console.log(deepGet(obj, 'a.b.e'));
console.log(deepGet(obj, 'a.b.f'));
console.log(deepGet(obj, 'a.b.x', 'default'));
console.log(deepGet(obj, 'x.y.z', 'not found'));
function deepGet(obj, path, defaultValue = undefined) {
if (!obj || typeof path !== 'string') return defaultValue;
const keys = path
.replace(/\[(\d+)\]/g, '.$1')
.split('.')
.filter((key) => key !== '');
let result = obj;
for (const key of keys) {
if (result === null || result === undefined) {
return defaultValue;
}
const index = isNaN(key) ? key : Number(key);
result = result[index];
}
return result === undefined ? defaultValue : result;
}
const complexObj = {
users: [
{ name: 'Alice', hobbies: ['reading', 'coding'] },
{ name: 'Bob', hobbies: ['gaming', 'music'] },
],
config: {
settings: {
theme: 'dark',
languages: ['zh', 'en'],
},
},
};
console.log(deepGet(complexObj, 'users[0].name'));
console.log(deepGet(complexObj, 'users[1].hobbies[0]'));
console.log(deepGet(complexObj, 'config.settings.languages[1]'));
console.log(deepGet(complexObj, 'users[2].name', 'Unknown'));