此阶段给自己定的目标是:做过的这些题每天坚持继续刷二遍,每道题做过之后开始尝试多解法尝试解题。上一阶段是感知都有什么题目,此阶段主要系统化常规题解套路知识,牢记牢记此阶段目的。
题号:938
var rangeSumBST = function (root, low, high) {
let result = 0
//中序遍历
let helper = (node) => {
if (node == null) {
return
}
helper(node.left)
//处理当前节点
if (node.val >= low && node.val <= high) {
result += node.val
}
helper(node.right)
}
helper(root)
return result
};
题号:460
var LFUCache = function (capacity) {
//记录最大容量
this.capacity = capacity
//记录缓存数据
this.lists = []
//标识一个最近的时间戳
//记录最近一次操作的时间
this.latesttime = null
};
LFUCache.prototype.get = function (key) {
let obj = this.findObj(key)
if (obj) {
obj.count++
//更新时间
this.latesttime++
obj.time = this.latesttime
this.sortLists()
return obj.value
} else {
return -1
}
};
LFUCache.prototype.put = function (key, value) {
if (this.capacity == 0) {
//do nothing
return
}
let obj = this.findObj(key)
if (obj) {
//update value
obj.count++
this.latesttime++
obj.time = this.latesttime
obj.value = value
} else {
if (this.lists.length == this.capacity) {
this.lists.shift()
}
//insert value
let obj = {}
obj.key = key
obj.count = 1
if (this.latesttime == null) {
this.latesttime = 10086
} else {
this.latesttime++
}
obj.time = this.latesttime
obj.value = value
this.lists.push(obj)
}
//sort value
this.sortLists()
};
LFUCache.prototype.findObj = function (key) {
for (let i = 0; i < this.lists.length; i++) {
let obj = this.lists[i]
if (obj.key === key) {
return obj
}
}
return null
}
LFUCache.prototype.sortLists = function () {
this.lists.sort((a, b) => {
if (a.count - b.count == 0) {
return a.time - b.time
}
return a.count - b.count
})
}
题号:148
var sortList = function (head) {
// 开辟一个数组空间
let arr = []
while (head) {
arr.push(head)
head = head.next
}
//排序数组中节点
arr.sort((a, b) => {
return a.val - b.val
})
//遍历数组设置next指针
for (let i = 0; i < arr.length; i++) {
let curNode = arr[i]
if (i > 0) {
let preNode = arr[i - 1]
preNode.next = curNode
}
curNode.next = null
}
return arr[0] ? arr[0] : null
};
//递归归并排序
var sortList = function (head) {
if (head == null) {
return null
}
if (head.next == null) {
return head
}
//快慢指针找中点
let slow = head, fast = head.next
while (fast && fast.next) {
fast = fast.next.next
slow = slow.next
}
//从slow处断开
let tmp = slow.next
slow.next = null
//去排序左边的链表
let list1 = sortList(head)
//去排序右边的链表
let list2 = sortList(tmp)
//合并有序链表
//排完序合并左右序列
//设置一个头结点方便下面的逻辑处理
let result = new ListNode()
let curNode = result
while (list1 && list2) {
if (list1.val > list2.val) {
curNode.next = list2
curNode = list2
list2 = list2.next
} else {
curNode.next = list1
curNode = list1
list1 = list1.next
}
curNode.next = null
}
if (list1) {
curNode.next = list1
}
if (list2) {
curNode.next = list2
}
return result.next
};