30天刷题挑战(二十七)

题目来源: LeetCode 75 面试经典 150 题

739. 每日温度

思路

单调栈,从数组右边开始遍历,比当前值小的就入栈,比当前值大的将它的索引放入结果数组,

代码

js 复制代码
/**
 * @param {number[]} temperatures
 * @return {number[]}
 */
var dailyTemperatures = function(temperatures) {
  const stack = []
  const res = Array(temperatures.length).fill(0);

  for (let i = temperatures.length - 1; i >= 0; i--) {
    while (stack.length && temperatures[i] >= temperatures[stack[stack.length - 1]]) {
      stack.pop()
    }

    if (stack.length) {
      res[i] = stack[stack.length - 1] - i
    }
    stack.push(i)
  }

  return res;
};

901. 股票价格跨度

思路

初始化一个栈和一个当前天数,在 next 方法中每次去栈顶找比当前值小的数,如果栈顶值小于当前值就出栈,将当前值和天数入栈。

代码

js 复制代码
var StockSpanner = function() {
  this.curDay = -1
  this.stack = [[-1, Infinity]]
};

/** 
 * @param {number} price
 * @return {number}
 */
StockSpanner.prototype.next = function(price) {
  while (price >= this.stack[this.stack.length - 1][1]) {
    this.stack.pop();
  }
  this.stack.push([++this.curDay, price]);

  return this.curDay - this.stack[this.stack.length - 2][0];
};

/**
 * Your StockSpanner object will be instantiated and called as such:
 * var obj = new StockSpanner()
 * var param_1 = obj.next(price)
 */

380. O(1) 时间插入、删除和获取随机元素

思路

使用一个数组存储数据,使用一个 Map 保存数据在数组中的索引值,以到达 O(1) 的时间复杂度

代码

js 复制代码
var RandomizedSet = function() {
    this.nums = [];
    this.indices = new Map();
};

RandomizedSet.prototype.insert = function(val) {
    if (this.indices.has(val)) {
        return false;
    }
    let index = this.nums.length;
    this.nums.push(val);
    this.indices.set(val, index);
    return true;
};

RandomizedSet.prototype.remove = function(val) {
    if (!this.indices.has(val)) {
        return false;
    }
    let id = this.indices.get(val);
    this.nums[id] = this.nums[this.nums.length - 1];
    this.indices.set(this.nums[id], id);
    this.nums.pop();
    this.indices.delete(val);
    return true;
};

RandomizedSet.prototype.getRandom = function() {
    const randomIndex = Math.floor(Math.random() * this.nums.length);
    return this.nums[randomIndex];
};

本文完,感谢阅读。

相关推荐
程序员Xu1 小时前
【LeetCode热题100道笔记】二叉树的右视图
笔记·算法·leetcode
笑脸惹桃花1 小时前
50系显卡训练深度学习YOLO等算法报错的解决方法
深度学习·算法·yolo·torch·cuda
阿维的博客日记2 小时前
LeetCode 48 - 旋转图像算法详解(全网最优雅的Java算法
算法·leetcode
gnip2 小时前
Jst执行上下文栈和变量对象
前端·javascript
excel2 小时前
🐣 最简单的卷积与激活函数指南(带示例)
前端
GEO_YScsn2 小时前
Rust 的生命周期与借用检查:安全性深度保障的基石
网络·算法
程序员Xu2 小时前
【LeetCode热题100道笔记】二叉搜索树中第 K 小的元素
笔记·算法·leetcode
醉方休3 小时前
npm/pnpm软链接的优点和使用场景
前端·npm·node.js
拉不动的猪3 小时前
简单回顾下Weakmap在vue中为何不能去作为循环数据源,以及替代方案
前端·javascript·vue.js
How_doyou_do3 小时前
数据传输优化-异步不阻塞处理增强首屏体验
开发语言·前端·javascript