
你好,
您是否正在寻找一种存储唯一值、允许插入值、查找值总数和删除值的数据结构?套装是最佳选择。许多编程语言都包含内置的 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 < s.length; i++) {
if (!set.has(s[i])) {
set.add(s[i]);
ans = Math.max(ans, set.size);
} else {
while (s_index < i && set.has(s[i])) {
set.delete(s[s_index++]);
}
set.add(s[i]);
ans = Math.max(ans, set.size);
}
}
return ans;
};
/*
Example 1:
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
*/
说明:
函数 lengthoflongestsubstring 使用带有 set 的滑动窗口技术来查找不重复字符的最长子字符串:
就是这样,如果您有任何疑问或任何建议或任何事情,请随时添加评论。
来源:
mdn(集)
以上就是JavaScript 中的 SET(初学者教程)的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号