ES6的
Set
你瞭解過嗎? Set 是一組Key的集合,它不存儲value。可是它的Key不能重複。總結起來就是一種無序且惟一
的數據結構。數組
- Set對象方法: new、 add、 delete、 has、 size
- 迭代Set: Set與Array互轉、求交集、差集等
let setKeys = new Set([1, 2, 3, 3]) // Set{1, 2, 3}
setKeys.add(3) // Set{1, 2, 3}
setKeys.delete(3) // Set{1, 2}
複製代碼
去重
let arr = [1, 1, 2, 2, 3, 3]
let arr2 = [...new Set(arr)] // [1, 2, 3]
複製代碼
const mySet = new Set([1, 2, 3, 4, 5])
mySet.has(1) // true
複製代碼
const s = new Set(1, 1, 2, 3, 4, 5)
const s2 = new Set([2, 3])
// 先將s轉換成數組, 經過數組的方法來篩選
const s3 = new Set( [...s].filter(n => s2.has(n)) )
複製代碼
const s = new Set(1, 1, 2, 3)
const s2 = new Set([2, 3])
// 先將s轉換成數組
const s3 = new Set( [...s].filter(n => !s2.has(n)) )
複製代碼
let mySet = new Set([1, 'text', {a:1} ])
for (let item of mySet) console.log(item) // 1, 'text', {a:1}
for (let item of mySet.values()) console.log(item) // 1, 'text', {a:1}
for (let item of mySet.keys()) console.log(item) // 1, 'text', {a:1}
for (let [key, value] of mySet.entries()) console.log(key, value)
// 1 1
// 'text' 'text'
// {a:1} {a:1}
能夠看到:Set數據結構key 和 value都是同樣的
複製代碼
Set ==> Array
let mySet = new Set([1, 2, 3])
[...mySet]
Array.from(mySet)
Array ==> Set
let arr = [1, 2, 3]
new Set(arr)
複製代碼
來看一道LeetCode題-349:markdown
給定兩個數組,編寫一個函數來計算它們的交集。數據結構
示例 1:
輸入:nums1 = [1,2,2,1], nums2 = [2,2]
輸出:[2]
示例 2:
輸入:nums1 = [4,9,5], nums2 = [9,4,9,8,4]
輸出:[9,4]
**說明:**
- 輸出結果中的每一個元素必定是惟一的。
- 咱們能夠不考慮輸出結果的順序。
複製代碼
/** * @param {number[]} nums1 * @param {number[]} nums2 * @return {number[]} */
var intersection = function(nums1, nums2) {
return [...new Set(nums1)].filter(n => nums2.includes(n))
}
時間複雜度O(n^2)
空間複雜度O(m)
複製代碼