//集合:无序且唯一的项的组合 ,用对象模拟集合
class Set {
constructor() {
this.items = {}
}
add(element) { //向集合中添加元素
if (!this.has(element)) {
this.items[element] = element; //键值名同为element
return true;
}
return false;
}
delete(element) { //从集合中移除一个元素
if (this.has(element)) {
delete this.items[element];
return true;
}
return false;
}
has(element) { //判断集合是否有该元素
return Object.prototype.hasOwnProperty.call(this.items, element);
}
clear() { //清空集合
this.items = {}
}
size() { //返回集合长度
let count = 0;
for (let key in this.items) {
if (this.items.hasOwnProperty(key)) {
count++;
}
}
return count;
}
values() { //返回包含集合所有值的数组
let array = [];
for (let key in this.items) {
if (this.items.hasOwnProperty(key)) {
array.push(key);
}
}
return array;
}
union(otherSet) { //并集
const unionSet = new Set();
this.values().forEach(value => {
unionSet.add(value);
})
otherSet.values().forEach(value => {
unionSet.add(value);
})
return unionSet;
}
intersection(otherSet) { //交集
const intersectionSet = new Set();
this.values().filter(value => {
if (otherSet.has(value)) {
intersectionSet.add(value);
}
})
return intersectionSet;
}
difference(otherSet) { //差集
const differenceSet = new Set();
this.values().filter(value => {
if (!otherSet.has(value)) {
differenceSet.add(value);
}
})
return differenceSet;
}
isSubsetOf(otherSet) { //子集
if (this.size() > otherSet.size()) {
return false;
}
let isSubset = true;
this.values().every(value => {
if (!otherSet.has(value)) {
isSubset = false;
return false;
}
return true;
})
return isSubset;
}
}
集合相关算法题
1.存在重复元素(力扣217)
var containsDuplicate = function (nums) {
let set = new Set();
for (let i = 0; i < nums.length; i++) {
if (set.has(nums[i])) {
return true;
} else {
set.add(nums[i])
}
}
return false
};
2.两个数组的交集(力扣349)
var intersection = function (nums1, nums2) {
let set = new Set();
nums1.filter(value => {
if (nums2.indexOf(value) !== -1) {
set.add(value);
}
})
return Array.from(set);
};
3.第三大的数(力扣414)
var thirdMax = function (nums) {
let arr = [...new Set(nums)].sort(function (a, b) { return a - b }) //按数字排序
if (arr.length === 1) {
return nums[0]
} else if (arr.length === 2) {
return Math.max(arr[0], arr[1])
} else {
return arr[arr.length - 3]
}
};