Skip to content

Instantly share code, notes, and snippets.

@otakustay
Created March 23, 2021 10:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save otakustay/f2934b7423470ecbdd370b5eb7955db4 to your computer and use it in GitHub Desktop.
Save otakustay/f2934b7423470ecbdd370b5eb7955db4 to your computer and use it in GitHub Desktop.
balanced-unique
function optimizedRemove<T>(sets: Array<Set<T>>, value: T): void {
// 如果N个数组中都有这个元素,那么我们只保留长度最短的数组中的那一份,其它的都删掉
const containedSets = sets.filter(s => s.has(value));
const setWithMinSize = containedSets.reduce((out, current) => (current.size <= out.size ? current : out));
containedSets.filter(s => s !== setWithMinSize).forEach(s => s.delete(value));
}
function makeBalancedUnique<T>(values: T[][]): T[][] {
// 转成Set,这样判断元素是否存在、删除元素性能更高
const sets = values.map(v => new Set(v));
// 打平所有的数组再去重,得到所有元素,拿这个元素一一去查找重复并去掉
const allValues = values.reduce(
(values, current) => {
current.forEach(v => values.add(v));
return values;
},
new Set()
);
for (const value of allValues) {
optimizedRemove(sets, value);
}
// 再转回数组来
return sets.map(s => [...s]);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment