2022.3.29
一、 LRU缓存淘汰算法
var LRUCache = function(capacity) {
this.capacity = capacity;
this.map = new Map();
};
LRUCache.prototype.get = function(key) {
if(this.map.has(key)){
const temp = this.map.get(key);
this.map.delete(key);
this.map.set(key, temp);
return temp;
}
else {
return -1;
}
};
LRUCache.prototype.put = function(key, value) {
if(this.map.has(key)){
this.map.delete(key);
}
this.map.set(key,value);
if(this.map.size > this.capacity) {
this.map.delete(this.map.keys().next().value);
}
};
2022、3、30
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的循环双向链表。要求不能创建任何新的节点,只能调整树中节点指针的指向。
var treeToDoublyList = function(root) {
if (!root) {
return;
}
let head = null;
let pre = head;
inorder(root);
head.left = pre;
pre.right = head;
return head;
function inorder(node) {
if (!node) return;
inorder(node.left, pre);
if (!pre) {
head = node;
} else {
pre.right = node;
}
node.left = pre;
pre = node;
inorder(node.right, pre);
}
};
作者:xin-tan
链接:https://leetcode-cn.com/problems/er-cha-sou-suo-shu-yu-shuang-xiang-lian-biao-lcof/solution/zhong-xu-bian-li-zhuan-hua-er-cha-sou-suo-shu-di-g/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
2022.3.31
var serialize = function(root) {
return rserialize(root, '');
};
var deserialize = function(data) {
const dataArray = data.split(",");
return rdeserialize(dataArray);
};
const rserialize = (root, str) => {
if (root === null) {
str += "None,";
} else {
str += root.val + '' + ",";
str = rserialize(root.left, str);
str = rserialize(root.right, str);
}
return str;
}
const rdeserialize = (dataList) => {
if (dataList[0] === "None") {
dataList.shift();
return null;
}
const root = new TreeNode(parseInt(dataList[0]));
dataList.shift();
root.left = rdeserialize(dataList);
root.right = rdeserialize(dataList);
return root;
}
var serialize = function(root) {
const rserialize = (root, str) => {
if (root === null) {
str += "None,";
} else {
str += root.val + '' + ",";
str = rserialize(root.left, str);
str = rserialize(root.right, str);
}
console.log(str)
return str;
}
return rserialize(root, '');
};
var deserialize = function(data) {
let arr = data.split(",");
console.log(arr)
};
2022.4.3
var serialize = function(root) {
let str = '';
const rserialize = (root) => {
if (root === null) {
str += "None,";
} else {
str += root.val + '' + ",";
str = rserialize(root.left, str);
str = rserialize(root.right, str);
}
return str;
}
return rserialize(root)
};
var deserialize = function(data) {
let arr = data.split(",");
const detraverse = (arr) => {
if (arr[0] === "None") {
arr.shift();
return null;
}
const root = new TreeNode(parseInt(arr[0]));
arr.shift();
root.left = detraverse(arr);
root.right = detraverse(arr);
return root;
}
return detraverse(arr)
};
记录序列化到底写过什么闹坑写法
我好像回了,但没完全学会,大冤种
var serialize = function(root) {
let res ='';
let preserialize = (root, res) =>{
if (root === null){
res.concat('NULL',',');
return;
}
res.concat(root.val, ',');
preserialize(root.left, res);
preserialize(root.right, res);
}
preserialize(root, res);
return res;
};
var deserialize = function(data) {
let preorder = data.split(' ').map(item => {
return Number.parseInt(item);
})
let nodes = [...preorder];
const predeserialize = (nodes) => {
const first = nodes.shift();
if(first === null) return null;
let root = new TreeNode(first);
root.left = predeserialize(nodes);
root.right = predeserialize(nodes);
return root;
}
return predeserialize(nodes);
};
-
突然看到困扰我4.1的那个问题:
序列化是将数据结构或对象转换为一系列位的过程,以便它可以存储在文件或内存缓冲区中,或通过网络连接链路传输,以便稍后在同一个或另一个计算机环境中重建。
设计一个算法来序列化和反序列化 二叉搜索树 。 对序列化/反序列化算法的工作方式没有限制。 您只需确保二叉搜索树可以序列化为字符串,并且可以将该字符串反序列化为最初的二叉搜索树。
编码的字符串应尽可能紧凑。
var serialize = function(root) {
let str = ''
const reSerialize = (root) => {
if(root === null){
str+="None,";
}else {
str += root.val+',';
reSerialize(root.left);
reSerialize(root.right);
}
return str;
}
return reSerialize(root)
};
var deserialize = function(data) {
console.log(data)
let arr = data.split(",");
console.log(arr)
const reDeserialize =(arr)=>{
let head = arr.shift();
if(head === "None") {
return null;
}
const root = new TreeNode(parseInt(head));
root.left = reDeserialize(arr);
root.right = reDeserialize(arr);
return root;
}
return reDeserialize(arr)
};
请实现两个函数,分别用来序列化和反序列化二叉树。
你需要设计一个算法来实现二叉树的序列化与反序列化。这里不限定你的序列 / 反序列化算法执行逻辑,你只需要保证一个二叉树可以被序列化为一个字符串并且将这个字符串反序列化为原始的树结构。
提示:输入输出格式与 LeetCode 目前使用的方式一致,详情请参阅 LeetCode 序列化二叉树的格式。你并非必须采取这种方式,你也可以采用其他的方法解决这个问题。
2022.4.5
给你一个正整数 n ,请你找出符合条件的最小整数,其由重新排列 n 中存在的每位数字组成,并且其值大于 n 。如果不存在这样的正整数,则返回 -1 。
注意 ,返回的整数应当是一个 32 位整数 ,如果存在满足题意的答案,但不是 32 位整数 ,同样返回 -1 。
var nextGreaterElement = function(n) {
const nStr = n + ''
const len = nStr.length
let max = nStr[len - 1]
const after = [max]
let before = -1
for (let i = len - 2; i >= 0; i--) {
if (nStr[i] < max) {
before = i
break;
} else {
max = nStr[i]
after.unshift(nStr[i])
}
}
if (before < 0) return -1
let num = nStr[before]
after.sort((a, b) => a - b)
for (let i = 0, len = after.length; i < len; i++) {
if (after[i] > num) {
const temp = after[i]
after[i] = num
num = temp
break
}
}
const ret = +(nStr.slice(0, before) + num + after.join(''))
return ret <= (2 ** 31 - 1) ? ret : -1
};
var MyQueue = function() {
this.inStack = [];
this.outStack = [];
};
MyQueue.prototype.push = function(x) {
this.inStack.push(x);
};
MyQueue.prototype.pop = function() {
if (!this.outStack.length) {
this.in2out();
}
return this.outStack.pop();
};
MyQueue.prototype.peek = function() {
if (!this.outStack.length) {
this.in2out();
}
return this.outStack[this.outStack.length - 1];
};
MyQueue.prototype.empty = function() {
return this.outStack.length === 0 && this.inStack.length === 0;
};
MyQueue.prototype.in2out = function() {
while (this.inStack.length) {
this.outStack.push(this.inStack.pop());
}
};
2022.4.6
给定一个字符串 s ,验证 s 是否是 回文串 ,只考虑字母和数字字符,可以忽略字母的大小写。
本题中,将空字符串定义为有效的 回文串 。
var isPalindrome = function(s) {
let str = s.toLowerCase();
let arr = [];
for(let i = 0 ;i < str.length; i++) {
if (str.charCodeAt(i) >= 97 && str.charCodeAt(i) <= 122)
arr.push(str[i])
if(str.charCodeAt(i) >= 48 && str.charCodeAt(i) <= 57)
arr.push(str[i]);
}
if (arr === []) return true
str = arr.join('')
str2 = arr.reverse().join('')
if(str === str2) return true
return false
};
var isPalindrome = function(head) {
let left = 0;
const res = [];
let sign = true;
while(head !== null){
res.push(head.val);
head = head.next;
}
let right = res.length-1;
while(left < right) {
if(res[left]!== res[right]) {
sign = false
}
left++;
right--;
}
return sign
};
编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 s 的形式给出。
不要给另外的数组分配额外的空间,你必须原地修改输入数组、使用 O(1) 的额外空间解决这一问题。
var reverseString = function(s) {
return s.reverse()
};
给定两个整数 n 和 k ,返回 1 ... n 中所有可能的 k 个数的组合。
-
/**
* @param {number} n
* @param {number} k
* @return {number[][]}
*/
var combine = function(n, k) {
const track = [];
const result = [];
const backtrack = (start)=> {
if(track.length === k){
result.push(track.slice());
}
for(let i = start ;i < n ;i++){
track.push(i+1);
backtrack(i+1);
track.pop()
}
}
backtrack(0)
return result
};
-
2022.4.9
var subsets = function(nums) {
let result = [];
let res = [];
const backtracking = (start) => {
result.push(res.slice())
for(let i = start; i < nums.length; i++){
res.push(nums[i]);
backtracking(i+1);
res.pop()
}
}
backtracking(0)
return result;
};
2022.4.12
var subsetsWithDup = function(nums) {
const result = [];
const path = []
const sortNums = nums.sort((a,b) => {
return a-b
})
function backtracing(startIndex, sortNums) {
result.push(path.slice(0))
if(startIndex > nums.length - 1) {
return
}
for(let i = startIndex; i < nums.length; i++) {
if(i > startIndex && nums[i] === nums[i-1]) {
continue
}
path.push(nums[i])
backtracing(i+1, sortNums)
path.pop()
}
}
backtracing(0, sortNums)
return result
};
var solveSudoku = function(board) {
function isValid(row, col, val, board) {
let len = board.length
for(let i = 0; i < len; i++) {
if(board[row][i] === val) {
return false
}
}
for(let i = 0; i < len; i++) {
if(board[i][col] === val) {
return false
}
}
let startRow = Math.floor(row / 3) * 3
let startCol = Math.floor(col / 3) * 3
for(let i = startRow; i < startRow + 3; i++) {
for(let j = startCol; j < startCol + 3; j++) {
if(board[i][j] === val) {
return false
}
}
}
return true
}
function backTracking() {
for(let i = 0; i < board.length; i++) {
for(let j = 0; j < board[0].length; j++) {
if(board[i][j] !== '.') continue
for(let val = 1; val <= 9; val++) {
if(isValid(i, j, `${val}`, board)) {
board[i][j] = `${val}`
if (backTracking()) {
return true
}
board[i][j] = `.`
}
}
return false
}
}
return true
}
backTracking(board)
return board
};
2022.4.13
var generateParenthesis = function (n) {
let set = new Set(['()']);
for (let c = 2; c <= n; c++) {
let nextSet = new Set();
for (const s of set) {
for (let j = 0; j <= s.length; j++) {
nextSet.add(s.slice(0, j) + '()' + s.slice(j));
}
}
set = nextSet;
}
return [...set];
};
var generateParenthesis = function (n) {
const res = [];
const dfs = (lRemain, rRemain, str) => {
if (str.length == 2 * n) {
res.push(str);
return;
}
if (lRemain > 0) {
dfs(lRemain - 1, rRemain, str + "(");
}
if (lRemain < rRemain) {
dfs(lRemain, rRemain - 1, str + ")");
}
};
dfs(n, n, "");
return res;
};
var generateParenthesis = function(n) {
if(n===0) return {}
const res = [];
const track = [];
backtrack(n, n, track, res);
return res;
};
const backtrack = (left, right, track, res) => {
if (left < 0 || right < 0){
return;
}
if (right < left) return;
if (left === 0 && right === 0) {
res.push(track)
return;
}
track.push('(');
backtrack(left-1, right, track, res);
track.pop();
track.push(')');
backtrack(left, right-1, track, res)
track.pop()
}
2022.4.17
var minDepth = function(root) {
if(root == null) {
return 0;
}
if(root.left == null && root.right == null) {
return 1;
}
let ans = Number.MAX_SAFE_INTEGER;
if(root.left != null) {
ans = Math.min(minDepth(root.left), ans);
}
if(root.right != null) {
ans = Math.min(minDepth(root.right), ans);
}
return ans + 1;
};
|