此阶段给自己定的目标是:做过的这些题每天坚持继续刷二遍,每道题做过之后开始尝试多解法尝试解题。上一阶段是感知都有什么题目,此阶段主要系统化常规题解套路知识,牢记牢记此阶段目的。
题号:剑指 Offer 59 - II
// 剑指 Offer 59 - II
var MaxQueue = function () {
this.queue = []
this.maxIdx = -1
};
/**
* @return {number}
*/
MaxQueue.prototype.max_value = function () {
if (this.queue.length == 0) {
return -1
} else {
return this.queue[this.maxIdx]
}
};
/**
* @param {number} value
* @return {void}
*/
MaxQueue.prototype.push_back = function (value) {
this.queue.push(value)
if (this.maxIdx == -1) {
this.maxIdx = 0
} else {
if (value > this.queue[this.maxIdx]) {
this.maxIdx = this.queue.length - 1
}
}
};
/**
* @return {number}
*/
MaxQueue.prototype.pop_front = function () {
if (this.queue.length == 0) {
return -1
} else {
this.maxIdx--
let shiftValue = this.queue.shift()
if (this.maxIdx == -1) {
//找最大值
this.findMaxValue()
}
return shiftValue
}
};
MaxQueue.prototype.findMaxValue = function () {
this.maxIdx = 0
for (let i = 1; i < this.queue.length; i++) {
if (this.queue[i] > this.queue[this.maxIdx]) {
this.maxIdx = i
}
}
}
题号:剑指offer 22
//剑指offer 22
//2次遍历
var getKthFromEnd = function (head, k) {
let total = 0, dumyNode = new ListNode(-1)
dumyNode.next = head, curNode = dumyNode
//找节点总数
while (curNode.next) {
total++
curNode = curNode.next
}
curNode = dumyNode
let step = total - k + 1
while (step != 0) {
curNode = curNode.next
step--
}
return curNode
};
//利用栈
var getKthFromEnd = function (head, k) {
let stack = [], curNode = head
while (curNode) {
stack.push(curNode)
curNode = curNode.next
}
while (k != 1) {
stack.pop()
k--
}
return stack.pop()
};
//利用递归
var getKthFromEnd = function (head, k) {
let result = null
let helper = (node) => {
if (node == null) {
return
}
helper(node.next)
k--
if (k == 0) {
result = node
}
}
helper(head)
return result
};
题号:7
var reverse = function (x) {
let result = 0, max = Math.pow(2, 31) - 1, min = -Math.pow(2, 31)
do {
let tmp = x % 10 //得到末尾余数
result = result * 10 + tmp
if (result > max || result < min) {
return 0
}
//减去余数然后/10挤掉末尾数字
x -= tmp
x /= 10
} while (x != 0);
return result
};