集合:一種無序且唯一的數(shù)據(jù)結(jié)構(gòu)
棧(后進(jìn)先出)隊列(先進(jìn)先出)鏈表(next指針)都是有序的數(shù)據(jù)結(jié)構(gòu)
集合中的元素都是唯一的。棧、隊列、鏈表中的元素都可以重復(fù)。
在ES6中新加了集合,名為set.所以可以直接在JS中使用。
集合的常用操作
1、去重(比如給數(shù)組去重,直接給他轉(zhuǎn)換為集合)
2、判斷元素是否在集合中
3、求交集
//去重
const arr = [1, 1, 2, 2, 3, 3]
//實例化一個set對象,把arr傳進(jìn)去,加...[]變?yōu)閿?shù)組
const arr2 = [...new Set(arr)]
arr2 = [1,2,3]
//判斷元素是否在集合中
//set 的has方法
const set = new Set(arr);
const has = set.has(4)
//has === true
//求交集
const set2 = new Set([2, 3, 4]);
//set沒有提供方法所以我們要轉(zhuǎn)化成數(shù)組再求交集,
//1、把set變?yōu)閿?shù)組 2、調(diào)用filter 篩選出set2也有的值,最終得到的數(shù)組再 new Set 把他實例化成新的集合
const set3 = new Set([...set].filter(item => set2.has(item)))
leetcod349 兩個數(shù)組的交集
給定兩個數(shù)組 nums1 和 nums2 ,返回 它們的交集 。
輸出結(jié)果中的每個元素一定是 唯一 的。
我們可以 不考慮輸出結(jié)果的順序 。
解題思路:無序且唯一,所以考慮到使用集合。
/**
* @param {number[]} nums1
* @param {number[]} nums2
* @return {number[]}
*/
var intersection = function(nums1, nums2) {
const set2 = new Set(nums2) //將nums2 變?yōu)榧? //通過數(shù)組的filter來篩選與set2中的交集,再變?yōu)榧先ブ兀? const nums3 = new Set(nums1.filter(item => set2.has(item)))
//再變?yōu)閿?shù)組 并return
const nums4 = [...nums3]
return nums4
};
另一種解法,用的數(shù)組原生includes
新思路 用集合對nums1去重
遍歷nums1篩選出nums2也包含的值
return [...new Set(nums1)].filter(n=>nums2.includes(n))
時間復(fù)雜度:里面有一個filter循環(huán),同時還進(jìn)行了includes操作,兩個時間復(fù)雜度都是O(n),也就是一個嵌套 所以時間復(fù)雜度是 O (m*n)m就是去重后數(shù)組的長度,n是nums2的長度
空間復(fù)雜度:nums1/2都是已有的存儲 額外的就是這個去重后的nums1這個數(shù)組
O(m)m就是去重后數(shù)組的長度
前端與集合:ES6中的Set
Set操作
使用Set對象:new(實例化) add delete has size
let mySet = new Set()
add
mySet.add(1)
Set(1) {1}
mySet.add(5)
Set(2) {1, 5}
mySet.add(5)
Set(2) {1, 5}
mySet.add('fuck')
Set(3) {1, 5, 'fuck'}
let o = {a:777}
mySet.add(o)
Set(4) {1, 5, 'fuck', {…}}
mySet.add({a:777})
Set(5) {1, 5, 'fuck', {…}, {…}}
兩個對象看起來一樣但是再內(nèi)存中存儲的位置不同,本質(zhì)上是兩個不同的對象。
has
mySet.has('1')
false
mySet.has(1)
true
mySet.has(o)
true
delete
Set(5) {1, 5, 'fuck', {…}, {…}}
mySet.delete(5)
Set(4) {1, 'fuck', {…}, {…}}
size獲取當(dāng)前集合的尺寸 也就是長度把
迭代Set: 多種迭代方法、Set與Array互轉(zhuǎn)、求交集、差集
迭代方法
for(let n of mySet){console.log(n)}
1
5
fuck
{a: 777}
{a: 777}
for(let n of mySet.keys()){console.log(n)}
for(let n of mySet.values()){console.log(n)}
都可以迭代出來,所以對于Set Keys和Value是一樣的
for(let[key,value] n of mySet.entries()){console.log(key,value)}
使用entries方法可以看出他們是一模一樣的
entries() 方法返回一個數(shù)組的迭代對象,該對象包含數(shù)組的鍵值對 (key/value)。
Set與Array互轉(zhuǎn)
Set轉(zhuǎn)數(shù)組
const myArr = [...mySet]
const myArr = Array.from(mySet)
數(shù)組轉(zhuǎn)Set
const mySet2 = new Set(myArr)
求交集
const set2 = new Set([2, 3, 4]);
//set沒有提供方法所以我們要轉(zhuǎn)化成數(shù)組再求交集,
//1、把set變?yōu)閿?shù)組 2、調(diào)用filter 篩選出set2也有的值,最終得到的數(shù)組再 new Set 把他實例化成新的集合
const set3 = new Set([...set].filter(item => set2.has(item)))
差集
set1
set2
求set2中沒set1中有的值
const difference = new Set([...set].filter(item => !set2.has(item)))
就加一個感嘆號代表否定
```以