javascript - Javascript - 获取数组中最大数组总和的最佳方法
问题描述
我有以下数组:
arr = [
[ 1, 1, 1, 1, 1, 1, 1 ],
[ 1, 1, 0, 0, 1, 1, 0 ],
[ 1, 0, 0, 0, 1, 0, 0 ],
[ 0, 0, 0, 0, 0, 0, 0 ],
[ 0, 1, 0, 1, 0, 0, 2 ],
[ 1, 0, 0, 1, 0, 2, 4 ],
[ 0, 0, 0, 0, 2, 4, 4 ],
[ 0, 0, 0, 0, 4, 4, 0 ],
[ 1, 1, 1, 0, 0, 0, 0 ],
[ 1, 1, 0, 2, 0, 0, 2 ],
[ 1, 0, 0, 4, 0, 2, 0 ],
[ 0, 0, 0, 4, 2, 0, 0 ],
[ 0, 0, 2, 0, 0, 0, 1 ],
[ 0, 2, 4, 0, 0, 1, 2 ],
[ 2, 4, 4, 2, 1, 2, 4 ],
[ 4, 4, 0, 0, 2, 4, 0 ]
]
目前,我正在arr
像这样获得 ie 19中的最大数组总和
function getMaxSum(arr) {
return arr.map(e => e.reduce((a, b) => a + b, 0)).sort((a,b) => a - b)[arr.length - 1];
}
- 我需要知道有没有更好的方法来实现这一点?
我使用原始数组的数组长度来获取结果数组的最后一个元素,因为在这种情况下,原始数组和结果数组的长度是相同的。如果情况不同,那么我如何在此处使用结果数组的长度:
return arr.map(e => e.reduce((a, b) => a + b, 0)).sort((a,b) => a - b)[ HERE - 1];
解决方案
不是一个巨大的改进,但将值传播到Math.max
const data = [
[ 1, 1, 1, 1, 1, 1, 1 ],
[ 1, 1, 0, 0, 1, 1, 0 ],
[ 1, 0, 0, 0, 1, 0, 0 ],
[ 0, 0, 0, 0, 0, 0, 0 ],
[ 0, 1, 0, 1, 0, 0, 2 ],
[ 1, 0, 0, 1, 0, 2, 4 ],
[ 0, 0, 0, 0, 2, 4, 4 ],
[ 0, 0, 0, 0, 4, 4, 0 ],
[ 1, 1, 1, 0, 0, 0, 0 ],
[ 1, 1, 0, 2, 0, 0, 2 ],
[ 1, 0, 0, 4, 0, 2, 0 ],
[ 0, 0, 0, 4, 2, 0, 0 ],
[ 0, 0, 2, 0, 0, 0, 1 ],
[ 0, 2, 4, 0, 0, 1, 2 ],
[ 2, 4, 4, 2, 1, 2, 4 ],
[ 4, 4, 0, 0, 2, 4, 0 ]
]
function getMaxSum(arr) {
return Math.max(...arr.map(e => e.reduce((a, b) => a + b, 0)))
}
console.log(getMaxSum(data))
正如@Rajesh 指出的那样, Math.max 比排序更快:
const numbers = Array(10000).fill().map((x,i)=>i);
const max = numbersIn => Math.max(...numbersIn);
const getMaxViaSort = numbersIn => numbersIn
.sort((a, b) => a > b ? -1 : 1)[0]
console.time('max');
max(numbers);
console.timeEnd('max');
console.time('max via sort');
getMaxViaSort(numbers);
console.timeEnd('max via sort');
推荐阅读
- reactjs - 如何从视图将参数传递给 React
- boolean-logic - 布尔 SKI 逻辑
- python - Pytest Cache Fixture with Pickle 而不是 JSON
- reactjs - 为什么我的空间使用 Material UI Grid System 变成了一条新线?
- c# - 这是让 C# 类共享对象的有效方法吗?
- javascript - 我的任务是在括号中传输字符串长度(javascript)
- c# - 如何在对象内插入对象?
- javascript - ERR_HTTP_HEADERS_SENT:在将标头发送到客户端节点后无法设置标头 Node js Express Firebase ERROR
- python - 删除关键字前以不同方式表达的数字
- javascript - 从图像切换到另一个图像时缩放第二个图像