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];
};

本文完,感谢阅读。

相关推荐
释怀°Believe2 分钟前
Daily算法刷题【面试经典150题-7️⃣位运算/数学/】
算法·面试·职场和发展
PieroPc3 分钟前
用FastAPI 后端 和 Vue3 前端写一个博客系统 例
前端·vue·fastapi
2401_8762213412 分钟前
因数个数、因数和、因数积
c++·算法
xiaoyustudiowww13 分钟前
fetch异步简单版本(Tomcat 9)
java·前端·tomcat
TOPGUS13 分钟前
谷歌Chrome浏览器即将对HTTP网站设卡:突出展示“始终使用安全连接”功能
前端·网络·chrome·http·搜索引擎·seo·数字营销
C_心欲无痕20 分钟前
ts - 模板字面量类型与 `keyof` 的魔法组合:`keyof T & `on${string}`使用
linux·运维·开发语言·前端·ubuntu·typescript
云里雾里!22 分钟前
LeetCode 744. 寻找比目标字母大的最小字母 | 从低效到最优的二分解法优化
算法·leetcode
CCPC不拿奖不改名25 分钟前
网络与API:HTTP基础+面试习题
网络·python·网络协议·学习·http·面试·职场和发展
一勺菠萝丶25 分钟前
Java 后端想学 Vue,又想写浏览器插件?
java·前端·vue.js
无限码力26 分钟前
华为OD技术面真题 - 计算机网络 - 3
计算机网络·华为od·面试·华为od技术面真题·华为od面试八股文·华为od技术面计算机网络相关