你好,
您是否正在寻找一种存储唯一值、允许插入值、查找值总数和删除值的数据结构?套装是最佳选择。许多编程语言都包含内置的 set 数据结构,javascript 也不例外。让我们更深入地了解集合的工作原理。
设置是什么?
set 是一种数据结构,可让您存储任何类型的唯一值,无论是原始值还是对象引用。该集合允许执行 o(1) 时间复杂度的插入、删除、更新和大小操作。这使得设置更快、更高效。
套装旨在提供快速访问时间。它们的实现方式通常使查找项目比简单地逐项检查更快。典型的实现可以是哈希表(o(1) 查找)或搜索树(o(log(n)) 查找)。
要点
立即学习“Java免费学习笔记(深入)”;
基本方法
示例
// 1. create a new set and use the .add() method to add elements
const myset = new set();
myset.add(10);
myset.add(20);
myset.add(30);
console.log(myset); // output: set { 10, 20, 30 }
// 2. check if the set has a specific element using .has() method
console.log(myset.has(20)); // output: true
console.log(myset.has(40)); // output: false
// 3. delete an element from the set using .delete() method
myset.delete(20);
console.log(myset); // output: set { 10, 30 }
// 4. iterate over the set using .keys() method
// in sets, .keys() and .values() do the same thing
for (const key of myset.keys()) {
console.log(key);
}
// output:
// 10
// 30
// 5. get the size of the set using .size property
console.log(myset.size); // output: 2
leetcode问题设置示例:
3.没有重复字符的最长子串
给定一个字符串 s,找到最长的不包含重复字符的子串的长度。
解决方案
/**
* @param {string} s
* @return {number}
*/
var lengthOfLongestSubstring = function(s) {
let set = new Set();
let ans = 0;
let s_index = 0;
for (let i = 0; i
<p>说明:<br>
函数 lengthoflongestsubstring 使用带有 set 的滑动窗口技术来查找不重复字符的最长子字符串:</p>
就是这样,如果您有任何疑问或任何建议或任何事情,请随时添加评论。
来源:
mdn(集)