javascript - 如何根据计算量大的键函数有效地对数组进行排序?
问题描述
我问了这个关于使用键函数对数组进行排序的问题,结果发现无法避免使用比较函数。
问题是
- 我有一个计算量很大的关键函数,我不得不把它变成一个比较函数
- 我正在对一组对象进行排序,这意味着我不能使用哈希表来记忆我的关键函数的结果
这是一个示例数组和(便宜的)键功能:
myArr = [{'foo': 5, 'bar': 'hello'}, {'foo': 3, 'bar': 'world'}];
keyFunc = obj => obj.foo; // sort by the value of the `foo` attribute
myArr.sort(???);
// result should be [{'foo': 3, 'bar': 'world'}, {'foo': 5, 'bar': 'hello'}]
鉴于这些情况,如何有效地对数组进行排序?
解决方案
由于我们希望每个数组元素只运行一次昂贵的键函数,我们别无选择,只能使用某种记忆。将键值与每个元素相关联的最简单方法可能是创建一个[key, element]
对数组,然后我们可以对其进行排序:
myArr = [{'foo': 5, 'bar': 'hello'}, {'foo': 3, 'bar': 'world'}];
keyFunc = obj => obj.foo;
// compute the key of each array element
keyedArr = myArr.map(obj => [keyFunc(obj), obj]);
// sort the array based on the key
keyedArr.sort((a, b) => a[0] - b[0])
// remove the key values from the array
result = keyedArr.map(pair => pair[1]);
// result: [{'foo': 3, 'bar': 'world'}, {'foo': 5, 'bar': 'hello'}]
请注意,这仅在 key 函数返回数字时才有效。
推荐阅读
- javascript - JS通过命令和任意数字分隔字符串
- python - 如何在事件 wxWidgets 中传递自定义数据
- python - Python XLWings Anaconda 新手 - 安装/基本问题
- c# - EFCore:无法确定导航属性表示的关系
- maximo - 我们可以在 Maximo 启动中心有条件地隐藏“帮助”菜单选项吗?
- java - 代码内存利用率快速增加 - Spring Boot
- python - Python Selenium - browser.find_element_by_class_name - 有时返回错误?
- amazon-web-services - 为什么我得到 /bin/sh: aws: command not found in local-exec 配置程序?
- python - ContentTypeError: 0, message='尝试使用意外的 mimetype 解码 JSON
- css - 具有不同列高的多列布局