求助:根据分数数组生成带同分数同排名的结果数组
分数数组的排名实现方案
核心思路
要实现分数对应排名(高分靠前、同分同排名),可以分三步完成:
- 提取原数组中的唯一分数,按降序排序,确定每个分数的排名位次
- 建立「分数-排名」的映射关系,避免重复计算
- 遍历原分数数组,通过映射快速生成每个位置的排名值
Python 实现示例
scores = [20, 6, 5, 15, 6, 3, 3, 11, 9, 3] # 1. 去重并降序排序唯一分数 sorted_unique = sorted(set(scores), reverse=True) # 2. 构建分数到排名的映射(索引+1对应排名) rank_dict = {score: idx + 1 for idx, score in enumerate(sorted_unique)} # 3. 生成最终排名数组 result = [rank_dict[score] for score in scores] print(result) # 输出: [1, 5, 6, 2, 5, 7, 7, 3, 4, 7]
JavaScript 实现示例
const scores = [20, 6, 5, 15, 6, 3, 3, 11, 9, 3]; // 1. 去重并降序排序唯一分数 const sortedUnique = [...new Set(scores)].sort((a, b) => b - a); // 2. 构建分数到排名的映射 const rankMap = {}; sortedUnique.forEach((score, index) => { rankMap[score] = index + 1; }); // 3. 生成最终排名数组 const result = scores.map(score => rankMap[score]); console.log(result); // 输出: [1, 5, 6, 2, 5, 7, 7, 3, 4, 7]
逻辑说明
- 去重排序后,唯一分数的顺序直接对应排名优先级:第一个元素是最高分,对应排名1,第二个对应排名2,以此类推
- 映射字典的作用是将分数和排名绑定,遍历原数组时只需查表就能得到结果,时间复杂度更低
内容的提问来源于stack exchange,提问作者Jekis Osipov
相关产品推荐
相关产品推荐

