首页 > 其他分享 >leetcode 中等(设计):[146, 155, 208, 211, 284, 304, 307, 341, 355, 380]

leetcode 中等(设计):[146, 155, 208, 211, 284, 304, 307, 341, 355, 380]

时间:2023-02-01 22:11:16浏览次数:53  
标签:146 function 155 val 211 word return prototype data

目录

146. LRU 缓存

var LRUCache = function (capacity) {
  this.capacity = capacity;
  this.map = new Map();
};
LRUCache.prototype.get = function (key) {
  if (this.map.has(key)) {
    let value = this.map.get(key);
    this.map.delete(key);
    this.map.set(key, value);
    return value;
  }
  return -1;
};

LRUCache.prototype.put = function (key, value) {
  this.map.delete(key);
  this.map.set(key, value);
  if (this.map.size > this.capacity) {
    this.map.delete(this.map.keys().next().value);
  }
};

155. 最小栈

var MinStack = function () {
  this.data = [];
};

MinStack.prototype.push = function (val) {
  this.data.push(val);
};
MinStack.prototype.pop = function () {
  this.data.pop();
};
MinStack.prototype.top = function () {
  return this.data[this.data.length - 1];
};
MinStack.prototype.getMin = function () {
  return Math.min(...this.data);
};

208. 实现 Trie (前缀树)

var Trie = function () {
  this.data = {};
};

Trie.prototype.insert = function (word) {
  this.data[word] = word;
};

Trie.prototype.search = function (word) {
  return !!this.data[word];
};

Trie.prototype.startsWith = function (prefix) {
  for (const key in this.data) {
    if (this.data[key].startsWith(prefix)) {
      return true;
    }
  }
  return false;
};

211. 添加与搜索单词 - 数据结构设计

var WordDictionary = function () {
  this.data = {};
};

WordDictionary.prototype.addWord = function (word) {
  if (!this.data[word.length]) {
    // 键为单词长度,值为同长度的单词集合
    this.data[word.length] = [];
  }
  this.data[word.length].push(word);
};

WordDictionary.prototype.search = function (word) {
  const len = word.length;
  if (!this.data[len]) return false;
  if (!word.includes(".")) return this.data[len].includes(word); // 普通字符串,直接从等长单词集合中查找即可

  // 否则是正则表达式,先创建正则表达式对象
  const reg = new RegExp(word);
  return this.data[len].some((item) => reg.test(item));
};

284. 顶端迭代器

var PeekingIterator = function (iterator) {
  this.data = [];
  while (iterator.hasNext()) this.data.push(iterator.next());
  this.index = 0;
  this.size = this.data.length;
};

PeekingIterator.prototype.peek = function () {
  return this.data[this.index];
};

PeekingIterator.prototype.next = function () {
  return this.data[this.index++];
};

PeekingIterator.prototype.hasNext = function () {
  return this.index < this.size;
};

304. 二维区域和检索 - 矩阵不可变

var NumMatrix = function (matrix) {
  this.data = matrix;
};

NumMatrix.prototype.sumRegion = function (row1, col1, row2, col2) {
  let sum = 0;
  for (let i = row1; i <= row2; i++) {
    for (let j = col1; j <= col2; j++) {
      sum += this.data[i][j];
    }
  }
  return sum;
};

307. 区域和检索 - 数组可修改

var NumArray = function (nums) {
  this.data = nums;
};
NumArray.prototype.update = function (index, val) {
  this.data[index] = val;
};
NumArray.prototype.sumRange = function (left, right) {
  let sum = 0;
  for (let i = left; i <= right; i++) {
    sum += this.data[i];
  }
  return sum;
};

341. 扁平化嵌套列表迭代器

// 方法一:
var NestedIterator = function (nestedList) {
  this.list = [];
  this.traverse(nestedList);
};
NestedIterator.prototype.traverse = function (arr) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i].isInteger()) {
      this.list.push(arr[i].getInteger()); // 是Integer
    } else {
      this.traverse(arr[i].getList()); // 是List,递归调用
    }
  }
};
NestedIterator.prototype.hasNext = function () {
  return this.list.length > 0;
};
NestedIterator.prototype.next = function () {
  return this.list.shift();
};

// 方法二:
var NestedIterator_1 = function (nestedList) {
  this.list = nestedList
    .toString()
    .split(",")
    .filter((val) => {
      return val != "";
    });
};
NestedIterator_1.prototype.toString = function () {
  if (this.isInteger()) {
    return this.getInteger() + "";
  } else {
    return this.getList().toString();
  }
};
NestedIterator_1.prototype.hasNext = function () {
  return this.list.length > 0;
};
NestedIterator_1.prototype.next = function () {
  return this.list.shift();
};

355. 设计推特

var Twitter = function () {
  this.tweets = {};
  this.user = {};
  this.time = 0;
};
Twitter.prototype.postTweet = function (userId, tweetId) {
  if (!this.tweets[userId]) {
    this.tweets[userId] = [];
  }
  this.tweets[userId].push({ tweetId, twitTime: this.time++ });
};

Twitter.prototype.getNewsFeed = function (userId) {
  let followsId = Array.from(this.user[userId] || {});
  followsId.push(userId);
  const allTwitters = followsId
    .reduce((prev, next) => prev.concat(this.tweets[next] || []), [])
    .sort((a, b) => b.twitTime - a.twitTime)
    .map((item) => item.tweetId);
  return Array.from(new Set(allTwitters)).slice(0, 10);
};

Twitter.prototype.follow = function (followerId, followeeId) {
  if (!this.user[followerId]) {
    this.user[followerId] = new Set();
  }
  this.user[followerId].add(followeeId);
};
Twitter.prototype.unfollow = function (followerId, followeeId) {
  if (this.user[followerId]) {
    this.user[followerId].delete(followeeId);
  }
};

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

var RandomizedSet = function () {
  this.data = new Set();
};

RandomizedSet.prototype.insert = function (val) {
  if (this.data.has(val)) {
    return false;
  } else {
    this.data.add(val);
    return true;
  }
};

RandomizedSet.prototype.remove = function (val) {
  return this.data.delete(val);
};

RandomizedSet.prototype.getRandom = function () {
  let random = Math.floor(Math.random() * this.data.size);
  return Array.from(this.data)[random];
};

标签:146,function,155,val,211,word,return,prototype,data
From: https://www.cnblogs.com/echoyya/p/17077062.html

相关文章

  • 2114
    一个 句子 由一些 单词 以及它们之间的单个空格组成,句子的开头和结尾不会有多余空格。给你一个字符串数组 sentences ,其中 sentences[i] 表示单个 句子 。请你......
  • ARC 155 题解
    A目前见过的最阴间的A。寻找规律,发现最后的回文串一定是由若干个周期拼起来的。当周期长度为偶数时,\(S\)和\(S'\)可以各拿半个周期。于是kmp求出border,再判一下,但......
  • 黑苹果i211网卡在macos Monterey及以上驱动方法
    ​原文来源于黑果魏叔官网,转载需注明出处。​两种方法:一、驱动换成别人修改后的AppleIGB.kext(可以前往黑果魏叔官网下载)。这么做一般情况用着没问题。但是如果你虚拟机桥接......
  • ARC155F Directable as Desired
    引理:对于给定的\(k\)个点,生成\(k\)个内向森林且根为给定的\(k\)个点的方案数为\(kn^{n-k-1}\)。证明:考虑执行\(n-k\)轮操作,每次选择任意一个点向不再其若连通块......
  • 0146-Go-HTTP 客户端
    环境Time2022-08-25Go1.19前言说明参考:https://gobyexample.com/http-clients目标使用Go语言的HTTP客户端。示例packagemainimport("bufio"......
  • L11U1-1-Writing a cover letter 20221126
    1GrammarExpressingasequenceDialogueFrank:ThisisalotharderthanwhatIthougtitwouldbe.Carmen:Iknow,right?Frank:Umm,butweneedanewaccountant......
  • 9、CSS权威指南--第5章(p155)字体
    5.1字体族CSS定义了五种通用字体族:衬线字体:这种字体中的字形宽度各异,而且有衬线。无衬线字体:这种字体中的字形宽度各异。等宽字体:等宽字体中的字形宽度一样。一般用......
  • oracle ORA-01461: 仅能绑定要插入 LONG 列的 LONG 值
    解决:将数据库中的数据类型改为:CLOB(存字符串大文本)或者BLOB(存二进制文件)博主问题场景:批量插入图片数据,图片太大,每张图片超过了4000字节,就会报错。将VARCHAR2修改为cl......
  • 20211217|写给一年后的培民的一封信
    亲爱的民:培民,见面如晤,没错这是一封来自一年前的信。自四月份考试结束,我就游荡于广州和深圳,记4.14下午自广州到深圳,第一站即是找立彬,我自知今年插本已是与我无缘,随即开始......
  • 20211217|写给一年后的立彬的一封信
    亲爱的彬:立彬,见面如晤,没错这是一封来自一年前的信。自四月份考试结束,我就游荡于广州和深圳,记4.14下午自广州到深圳,第一站即是找你,顶楼你留了门卡,大门你远程开,晚上下班我......