当前位置:网站首页>实现一个方法,找出数组中的第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中数组去重的几种方法
边栏推荐
- Standardize your own debug process
- Win11麦克风权限的开启方法
- [C Advanced] deeply explore the storage of data (in-depth analysis + interpretation of typical examples)
- Win11 hide input method status bar method
- [sql] usage of self connection
- Win11大小写提示图标怎么关闭?Win11大小写提示图标的关闭方法
- How to install with USB flash disk?
- AMD64 (x86_64) architecture ABI document:
- Qt 信号在多层次对象间传递 多层嵌套类对象之间信号传递
- Convert rich text to normal text
猜你喜欢

Anti electronic ink screen st7302

信息系统项目管理师必背核心考点(五十)合同内容约定不明确规定

Safety margin of mass consumption

记一次SQL优化

The difference between the world wide web, the Internet and the Internet
![[sql] usage of self connection](/img/92/92474343b4b4e6ea60453b4799cb55.jpg)
[sql] usage of self connection

如何用U盘进行装机?

How to reinstall win7 system?

How to design test cases according to the requirements of login testing?
![[detailed explanation of key and difficult points of document operation]](/img/f5/99c8cdf09763c66ab5d56cc96e50c7.png)
[detailed explanation of key and difficult points of document operation]
随机推荐
LeetCode·每日一题·剑指 Offer || 115.重建序列·拓扑排序
Self-supervised learning method to solve the inverse problem of Fokker-Planck Equation
snownlp库各功能及用法
Information system project managers must recite the core examination site (50). The contract content is not clearly stipulated
26 points that must be paid attention to for stability test
如何正确计算 Kubernetes 容器 CPU 使用率
Win11 method of changing disk drive letter
[detailed explanation of key and difficult points of document operation]
经典面试问题——OOP语言的三大特征
VOFA+ 串口调试助手
Usage of '...' in golang
对于稳定性测试必需关注的26点
LeetCode·83双周赛·6128.最好的扑克手牌·模拟
Golang 中‘...‘的用法
Machine learning foundation plan 0-2: what is machine learning? What does it have to do with AI?
FPGA_Vivado软件初次使用流程_超详细
朋友刚学完自动化测试就拿25Koffer,我功能测试何时才能到头?
Service gateway (zuul)
[NOIP2001 普及组]装箱问题
Win11隐藏输入法状态栏方法