集合是一種包含不一樣元素的數據結構。集合最重要的兩個特性是:首先,集合中的成員是無序的;其次,集合中不容許相同成員存在。算法
咱們必需要了解如下關於集合的定義:數組
對集合的操做有以下幾種:數據結構
咱們將使用JavaScript實現集合結構,各部分功能使用註釋說明。
存儲數據咱們使用的是數組。this
/** * Set() 定義集合類 */ function Set () { this.dataStore = [] this.add = add this.remove = remove this.size = size this.union = union this.intersect = intersect this.subset = subset this.difference = difference this.show = show this.contains = contains } /** * add() 該方法用於爲集合類添加值 * @param {*} data */ function add (data) { if (this.contains(data)) { return false } else { this.dataStore.push(data) return true } } /** * remove() 該方法用於爲集合類刪除值 * @param {*} data */ function remove (data) { let pos = this.dataStore.indexOf(data) if (pos > -1) { this.dataStore.splice(pos, 1) return true } else { return false } } /** * show() 該方法用於顯示集合中的全部元素 */ function show () { return this.dataStore } /** * size() 該方法用於獲取集合的長度 */ function size () { return this.dataStore.length } /** * union() 該方法用於求兩個集合的並集 * @param {*} set */ function union (set) { let tempSet = new Set() // 將當前集合中的元素加入到臨時集合中 for (let i = 0; i < this.size(); i++) { tempSet.add(this.dataStore[i]) } // 判斷第二個集合中的元素在臨時集合中是否存在,若不存在,則加入該元素 for (let i = 0; i < set.size(); i++) { if (!tempSet.contains(set.dataStore[i])) { tempSet.add(set.dataStore[i]) } } return tempSet } /** * intersect() 該方法用於求兩集合的交集 * @param {*} set */ function intersect (set) { let tempSet = new Set() // 遍歷set for (let i = 0; i < set.size(); i++) { // 當該集合中存在此元素,則將該元素插入至tempSet if (this.contains(set.dataStore[i])) { tempSet.add(set.dataStore[i]) } } return tempSet } /** * subset() 該方法用於判斷當前集合是否爲set集合的子集 * @param {*} set */ function subset (set) { // 當該集合的長度大於set集合的長度,則該集合不可能爲set集合的子集 if (this.size() > set.size()) { return false } for (let i of this.dataStore) { if (!set.contains(i)) { return false } } return true } /** * difference() 該方法用於返回屬於該集合但不屬於set集合的成員 * @param {*} set */ function difference (set) { let tempSet = new Set() for (let i of this.dataStore) { if (!set.contains(i)) { tempSet.add(i) } } return tempSet } /** * contains() 該方法用於判斷元素是否存在於集合中 * @param {*} data */ function contains (data) { if (this.dataStore.indexOf(data) > -1) { return true } else { return false } }
以上代碼,我的認爲很是重要的方法就是indexOf()
來判斷數組中是否存在該元素,經過該方法來判斷當前可否向集合中添加元素。code
使用JavaScript實現集合數據結構相對來講比較簡單。ip
參考資料:數據結構與算法JavaScript描述 第9章 集合 因爲書上的源代碼出現了錯誤,所以代碼根據實際運行結果作了相應修改。