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

如何在C#中统计数组元素出现次数并按次数降序输出?

解决数组元素出现次数统计及排序输出问题

核心解决思路是先通过键值对映射统计每个元素的出现次数,再对统计结果按出现次数降序排序,从根源避免重复输出的问题。以下是两种常用编程语言的实现方案:

Java 实现示例

1. 统计元素出现次数

使用HashMap存储元素与对应出现次数的映射,遍历数组完成计数:

import java.util.*;

public class MovieRentalStats {
    public static void main(String[] args) {
        int[] moviesRented = {17, 3, 3, 2, 2, 2, 1, 1, 1, 1};
        
        // 构建元素-次数映射表
        Map<Integer, Integer> countMap = new HashMap<>();
        for (int num : moviesRented) {
            countMap.put(num, countMap.getOrDefault(num, 0) + 1);
        }

2. 按出现次数降序排序

将映射表的条目转为列表,自定义排序规则实现降序:

// 转换为列表并按次数降序排序
        List<Map.Entry<Integer, Integer>> sortedEntries = new ArrayList<>(countMap.entrySet());
        sortedEntries.sort((entry1, entry2) -> entry2.getValue().compareTo(entry1.getValue()));

3. 按指定格式输出

遍历排序后的列表,输出符合要求的内容:

// 打印结果
        for (Map.Entry<Integer, Integer> entry : sortedEntries) {
            System.out.println(entry.getValue() + " occurrence of " + entry.getKey());
        }
    }
}

运行后输出:

4 occurrence of 1
3 occurrence of 2
2 occurrence of 3
1 occurrence of 17

Python 实现示例

利用collections.Counter可以更简洁地完成统计与排序:

from collections import Counter

movies_rented = [17, 3, 3, 2, 2, 2, 1, 1, 1, 1]

# 统计元素出现次数
count_dict = Counter(movies_rented)

# 按出现次数降序排序(若次数相同可追加元素值排序)
sorted_items = sorted(count_dict.items(), key=lambda x: (-x[1], x[0]))

# 按格式输出
for num, count in sorted_items:
    print(f"{count} occurrence of {num}")

输出结果与预期完全一致。

关于重复输出的原因

你之前直接遍历降序后的数组时,每个重复元素都会被单独处理一次,导致同一元素的统计结果被多次打印。而通过键值对映射统计后,每个元素仅保留一条记录,自然解决了重复输出的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 14:55:04