如何把一个带重复元素的集合拆分成多个不带重复的小集合?

如何把一个带重复元素的集合拆分成多个不带重复的小集合?

集合包含元素29,36,37,37,39,39,955,955,955,961,961,962,962
如何拆分成
29,36,37,39,955,961,962
37,39,955,961,962
955
三个小集合?


回答:

python版 (新手python 应该还有更好的写法)

datas = [29, 36, 37, 37, 39, 39, 955, 955, 955, 961, 961, 962, 962]

elementCounts = {}

maxCount = 0

for data in datas:

if data in elementCounts:

count = elementCounts[data]

else:

count = 0

elementCounts[data] = count + 1

if count + 1 > maxCount:

maxCount = count + 1

sets = []

for i in range(maxCount):

sets.append(set())

for key in elementCounts.keys():

count = elementCounts[key]

for i in range(count):

sets[i].add(key)

print(sets)


回答:

用字典:

const input = [29, 36, 37, 37, 39, 39, 955, 955, 955, 961, 961, 962, 962];

const elementCounts = {};

input.forEach((element) => {

elementCounts[element] = (elementCounts[element] || 0) + 1;

});

const sets = [];

Object.keys(elementCounts).forEach((element) => {

const count = elementCounts[element];

for (let i = 0; i < count; i++) {

if (!sets[i]) {

sets[i] = new Set();

}

sets[i].add(parseInt(element, 10));

}

});

console.log(sets);

输出:

[

Set(7) { 29, 36, 37, 39, 955, 961, 962 },

Set(5) { 37, 39, 955, 961, 962 },

Set(1) { 955 }

]


回答:

    val sourceArray: Array<Int> = arrayOf(29, 36, 37, 37, 39, 39, 955, 955, 955, 961, 961, 962, 962)

val array: MutableList<MutableSet<Int>> = ArrayList()

for ((index, value) in sourceArray.withIndex()) {

t2@ for (i in 0..index) {

if (array.size == i) {

array.add(HashSet())

array[i].add(value)

break@t2

} else {

if (array[i].add(value)) {

break@t2

}

}

}

}

以上是 如何把一个带重复元素的集合拆分成多个不带重复的小集合? 的全部内容, 来源链接: utcz.com/p/938898.html

回到顶部