当前位置:网站首页>实现一个方法,找出数组中的第k大和第m大的数字相加之和
实现一个方法,找出数组中的第k大和第m大的数字相加之和
2022-07-26 03:07:00 【二脸懵逼】
题目:实现一个方法,找出数组中的第k大和第m大的数字相加之和;
示例:
let arr = [1,2,4,4,3,5], k = 2, m = 4
findTopSum(arr, k, m); // 第2大的数是4,出现2次,第4大的是2,出现1次,所以结果为10
(自己写的,当然可能还有更简介的代码)
function bigSum(arr, k, m) {
//排序
arr = arr.sort(function (a, b) {
return b - a;
})
console.log('降序后的数组', arr)
//去重(是一个对象)
let newArr = new Set(arr);
//转为数组
let arr1 = [...newArr]
console.log('去重后的数组', arr1);
let temp1 = arr1[k - 1];
let temp2 = arr1[m - 1];
let total1 = 0;//计算相同元素的数量
let total2 = 0;
arr.forEach((item) => {
if (item == temp1) {
total1++;
}
if (item == temp2) {
total2++;
}
})
return (temp1 * total1 + temp2 * total2);
}
let result = bigSum([2, 4, 2, 8, 4, 2, 4, 5], 3, 4)
console.log('计算结果', result);

链接: js中数组去重的几种方法
边栏推荐
- [translation] announce Vites 13
- Multithreaded programming
- [NOIP2001 普及组] 最大公约数和最小公倍数问题
- The difference between the world wide web, the Internet and the Internet
- 【尤里复裂人】带你轻松理解——深拷贝和浅拷贝
- 记一次SQL优化
- Image recognition (VI) | activation function
- cmd cpm 命令汇总
- [detailed explanation of key and difficult points of document operation]
- 手把手教你依赖管理
猜你喜欢

(pc+wap) dream weaving template vegetable and fruit websites

STM32——DMA笔记
![[NOIP2001 普及组]装箱问题](/img/b7/1310b3e68d0ee016465fc069315af6.png)
[NOIP2001 普及组]装箱问题

Self-supervised learning method to solve the inverse problem of Fokker-Planck Equation

Opencv 在图像上进行标注(画框+写字)

Keyboardtraffic, a tool developed by myself to solve CTF USB keyboard traffic

图像识别(七)| 池化层是什么?有什么作用?

Difference between soft link and hard link

规范自己debug的流程

Autojs cloud control source code + display
随机推荐
STM32——PWM学习笔记
Detailed explanation of extended physics informedneural networks paper
.net serialize enumeration as string
Autojs cloud control source code + display
Oxycon 2022 network capture frontier conference is about to open!
一切的源头,代码分支策略的选择
How to effectively prevent others from wearing the homepage snapshot of the website
[steering wheel] use the 60 + shortcut keys of idea to share with you, in order to improve efficiency (live template & postfix completion)
Swin Transformer【Backbone】
[NOIP2001 普及组] 最大公约数和最小公倍数问题
Vofa+ serial port debugging assistant
Cloud native guide what is cloud native infrastructure
Neo4j import CSV data error: neo4j load CSV error: couldn't load the external resource
Nahamcon CTF 2022 babyrev reverse analysis
dataframe整理:datetime格式分拆;删除特定行;分组整合。
LeetCode·每日一题·剑指 Offer || 115.重建序列·拓扑排序
循环与分支(一)
这种动态规划你见过吗——状态机动态规划之股票问题(上)
朋友刚学完自动化测试就拿25Koffer,我功能测试何时才能到头?
Convert rich text to normal text