一、手写算法

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)

二、编程题

  1. // 33. 实现`Promise.allSettled()`
  2. // https://bigfrontend.dev/zh/problem/implement-Promise-allSettled
  1. /**
  2. * @param {Array<any>} promises - notice that input might contains non-promises
  3. * @return {Promise<Array<{status: 'fulfilled', value: any} | {status: 'rejected', reason: any}>>}
  4. */
  5. function allSettled(promises) {
  6. // your code here
  7. if (promises.length === 0) return Promise.resolve([]);
  8. let _promises = promises.map((item) =>
  9. item instanceof Promise ? item : Promise.resolve(item)
  10. );
  11. return new Promise((resolve, reject) => {
  12. let results = [];
  13. let count = _promises.length;
  14. _promises.forEach((promise, index) => {
  15. promise.then(
  16. (value) => {
  17. results[index] = {
  18. status: 'fulfilled',
  19. value: value,
  20. };
  21. count -= 1;
  22. if (count === 0) {
  23. resolve(results);
  24. }
  25. },
  26. (reason) => {
  27. results[index] = {
  28. status: 'rejected',
  29. reason: reason,
  30. };
  31. count -= 1;
  32. if (count === 0) {
  33. resolve(results);
  34. }
  35. }
  36. );
  37. });
  38. });
  39. }