【发布时间】:2019-08-15 02:25:28
【问题描述】:
我需要实现一个名为 findMode 的函数来查找数组的模式。假设数组仅包含整数。当函数被调用并且数组为空时,它返回 0。当函数被调用并且数组不为空时,它应该返回数组中出现频率最高的元素。如果一个数组包含多个模式,它应该返回模式的最小值。我需要创建一个中间数组,另一个数字数组来计算每个值出现的次数。这个数组应该使用数组的索引号来跟踪 b 中的数字被计算了多少次。
以下是我目前所拥有的:
import { print } from "....";
export let main = async () => {
let input = [2, 1, 1, 2, 1, 0]
print(mode(input))
};
export let findMode = (b: number[]): number => {
let newArr: number[] = []; /** this is the new number array created to store count, this is the intermediate array */
if (b.length === 0) {
return 0;
for (let i = 0; i < b.length; i++) {
};
main();
以下是预期/实际结果:
如果数组是 b[2,1,1,2,1,0],那么应该返回 1,如果我们打印我们创建的用于存储计数的数组,它应该打印 newArr[1,3,2]因为元素 0 出现了 1 次,元素 1 出现了 3 次,元素 2 出现了 2 次。我们的想法是从 0 作为输入数组中的元素到 0 作为中间数组中的索引。所以最后我们看到我们的最大出现次数(或中间数组中的最大元素)在索引 1 处为 3,因此模式为 1。
如果数组是 b[0,0,0,1,1,2,1,1] 那么应该返回 1。如果数组是 b[4,4,7,4,0,7] 那么应该返回 4。如果数组是 b[-4,-4,-1,3,5] 那么应该返回 -4。如果数组是 b[1,1,2,3,2] 则应返回 1,因为它是最小的模式。如果数组是 b[10,10,10,20,20,30] 那么应该返回 10。
【问题讨论】:
-
这是一个错字,已修复。
标签: arrays typescript for-loop return mode