一、手写算法
https://leetcode-cn.com/problems/design-a-stack-with-increment-operation/
思路
- 实现栈的基础操作
- 创建栈结构:栈顶,存放栈数据,最大栈容量
- 实现入栈push,出栈pop,维护栈顶元素即可
- increment方法,判断循环次数,执行相加操作
代码
```javascript /**- @param {number} maxSize */ var CustomStack = function(maxSize) { this.maxSize = maxSize; this.currentLength = 0; this.value = [] };
/**
- @param {number} x
- @return {void} */ CustomStack.prototype.push = function(x) { if(this.currentLength < this.maxSize){ this.value[this.currentLength] = x; this.currentLength++; } };
/**
- @return {number} */ CustomStack.prototype.pop = function() { if(this.currentLength > 0){ let val = this.value[this.currentLength - 1]; console.log(this.currentLength) this.currentLength—; return val; }else{ return -1 } };
/**
- @param {number} k
- @param {number} val
- @return {void} */ CustomStack.prototype.increment = function(k, val) { let len = k > this.currentLength ? this.currentLength :k for (let i = 0; i < len; i++) { this.value[i] = this.value[i] + val; } };
/**
- Your CustomStack object will be instantiated and called as such:
- var obj = new CustomStack(maxSize)
- obj.push(x)
- var param_2 = obj.pop()
- obj.increment(k,val)
*/
```
复杂度分析
- 时间复杂度:push,pop复杂度为O(1),increment复杂度为O(n)
- 空间复杂度:O(n)
二、编程题
// 33. 实现`Promise.allSettled()`// https://bigfrontend.dev/zh/problem/implement-Promise-allSettled
/*** @param {Array<any>} promises - notice that input might contains non-promises* @return {Promise<Array<{status: 'fulfilled', value: any} | {status: 'rejected', reason: any}>>}*/function allSettled(promises) {// your code hereif (promises.length === 0) return Promise.resolve([]);let _promises = promises.map((item) =>item instanceof Promise ? item : Promise.resolve(item));return new Promise((resolve, reject) => {let results = [];let count = _promises.length;_promises.forEach((promise, index) => {promise.then((value) => {results[index] = {status: 'fulfilled',value: value,};count -= 1;if (count === 0) {resolve(results);}},(reason) => {results[index] = {status: 'rejected',reason: reason,};count -= 1;if (count === 0) {resolve(results);}});});});}
