You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

多数组重复值统计及按计数降序排序实现方案咨询

多数组重复值检查器实现方案(计数+降序排序)

核心步骤

要实现需求中的功能,核心流程分为三步:扁平化数组→统计数字出现次数→过滤+排序,以下是具体实现建议和代码示例:

1. 扁平化多维度数组

将所有子数组合并成一个一维数组,这是统计的基础——只有一维数据才能高效统计每个数字的出现次数。

2. 统计数字出现次数

如果需要覆盖指定范围的数字(比如示例中的1-10,包含未出现的数字并计数为0),需要遍历目标数字范围统计;如果只需要统计出现过的数字,直接统计即可。

3. 过滤与排序

先过滤掉计数为0的条目,再按计数从高到低排序;若计数相同,可按数字升序/降序排列(示例目标中计数相同的数字按升序排列)。


Python 实现示例

from collections import Counter
import itertools

# 原始多数组数据
data = [
    [5, 6, 8, 4, 2],
    [2, 3, 4, 1, 8],
    [9, 3, 2, 1, 10]
]

# 1. 扁平化数组
flattened_data = list(itertools.chain(*data))

# 2. 统计1-10范围内每个数字的出现次数(含未出现的数字)
target_numbers = range(1, 11)
# 用Counter提升统计效率
counter = Counter(flattened_data)
count_result = {num: counter.get(num, 0) for num in target_numbers}

# 3. 过滤计数为0的项,按「计数降序→数字升序」排序
sorted_result = sorted(
    [(num, cnt) for num, cnt in count_result.items() if cnt > 0],
    key=lambda x: (-x[1], x[0])
)

# 格式化输出结果
print("number | count")
print("-------|------")
for num, cnt in sorted_result:
    print(f"{num:6} | {cnt:5}")

JavaScript 实现示例

// 原始多数组数据
const data = [
    [5, 6, 8, 4, 2],
    [2, 3, 4, 1, 8],
    [9, 3, 2, 1, 10]
];

// 1. 扁平化数组
const flattenedData = data.flat();

// 2. 统计1-10范围内每个数字的出现次数(含未出现的数字)
const countMap = new Map();
for (let num = 1; num <= 10; num++) {
    countMap.set(num, flattenedData.filter(n => n === num).length);
}

// 3. 过滤计数为0的项,按「计数降序→数字升序」排序
const sortedResult = Array.from(countMap.entries())
    .filter(([_, count]) => count > 0)
    .sort((a, b) => {
        if (b[1] !== a[1]) {
            return b[1] - a[1]; // 计数降序
        }
        return a[0] - b[0]; // 计数相同时数字升序
    });

// 格式化输出结果
console.log("number | count");
console.log("-------|------");
sortedResult.forEach(([num, count]) => {
    console.log(`${num.toString().padStart(6)} | ${count.toString().padStart(5)}`);
});

关键细节说明

  • 扁平化效率:使用语言内置的扁平化工具(如Python的itertools.chain、JS的flat())比手动嵌套循环效率更高,尤其数据量较大时更明显。
  • 范围统计:如果不需要覆盖指定数字范围,可直接统计出现过的数字,省略target_numbers相关逻辑,减少不必要的计算。
  • 排序规则:排序的key/比较函数可根据需求调整,比如计数相同时按数字降序,只需修改排序逻辑即可。

内容的提问来源于stack exchange,提问作者Dark

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 04:30:23