如果不小心网友来到了这里请网友自动飘走,浪费你们时间表示歉意。该系列博客的目的是:想作为自律工具和朋友一起每天刷几道题作为打卡督促的功能,没有什么可参考学习的东西,也不是刷博客量充大佬的目的
题号:538
//常规遍历
//翻转中序遍历
var convertBST = function (root) {
let sum = 0
//递归遍历
let helper = (node) => {
if (node == null) {
return
}
helper(node.right)
//处理当前节点
sum += node.val
node.val = sum
helper(node.left)
}
helper(root)
return root
};
题号:146
//过段时间再刷要自己写链表解决
var LRUCache = function (capacity) {
this.max = capacity
this.map = new Map()
this.stack = []
};
LRUCache.prototype.get = function (key) {
if (this.map.has(key)) {
//用过就是最新
let findIdx = this.stack.indexOf(key)
//删除原来key的位置
this.stack.splice(findIdx, 1)
this.stack.push(key)
return this.map.get(key)
} else {
return -1
}
};
LRUCache.prototype.put = function(key, value) {
if (this.map.has(key)) {
//用过就是最新
let findIdx = this.stack.indexOf(key)
//删除原来key的位置
this.stack.splice(findIdx, 1)
this.stack.push(key)
this.map.set(key,value)
} else {
if (this.stack.length == this.max) {
//满了
let key = this.stack.shift()
this.map.delete(key)
}
this.stack.push(key)
this.map.set(key,value)
}
};
题号:287
//复习二分法
var findDuplicate = function (nums) {
//nums里面元素范围在1~nums.length - 1之间
let left = 1, right = nums.length - 1
//二分法魔鬼细节1:到底需不需要left<=right
while (left < right) {
//二分法魔鬼细节2:相加溢出(当然我这里没写)
let mid = Math.floor((left + right) / 2)
let count = 0
nums.forEach((item) => {
if (item <= mid) {
count ++
}
});
//二分法魔鬼细节3:指针收缩到底加不加1减不减1
if (count > mid) {
//重复在左边区间
right = mid
} else {
left = mid + 1
}
}
return left
};