首页 > 解决方案 > 空间和时间的优化解决方案

问题描述

最近,一位比我年长的开发人员给了我一个看似很小的 JavaScript 编程挑战。

它类似于:

编写代码以在将新数字插入跟踪器类时持续跟踪最高、最低和平均温度。

使用这些方法编写一个类 TempTracker:

  • 一种插入新温度的方法。
  • 一种获得迄今为止我们见过的最高温度的方法
  • 一种获得迄今为止我们见过的最低温度的方法
  • 一种获取迄今为止我们看到的所有温度平均值的方法

优化空间和时间。

下面是我的解决方案(您可以在此处找到包括测试在内的完整源代码)。

class TempTracker {
    constructor() {
        this.temperatures = [];
    }

    all() {
        return [...this.temperatures];
    }

    clear() {
        this.temperatures.length = 0;
    }

    count() {
        return this.temperatures.length;
    }

    insert(temperature) {
        if (typeof temperature !== 'number' || Number.isNaN(temperature)) {
            throw new TypeError('must be a number');
        }

        this.temperatures.push(temperature);
    }

    add(temperature) {
        this.insert(temperature);
    }

    get length() {
        return this.count();
    }

    get lowest() {
        return this.check((temperatures) => Math.min(...temperatures));
    }

    get highest() {
        return this.check((temperatures) => Math.max(...temperatures));
    }

    get average() {
        return this.check((temperatures, length) => {
            const totalTemperature = temperatures.reduce(
                (acc, temperature) => acc + temperature,
                // eslint-disable-next-line
                0
            );

            return Number((totalTemperature / length).toFixed(2));
        });
    }

    // should be private method
    check(callback) {
        if (typeof callback !== 'function') {
            throw new TypeError('callback must be a function');
        }

        if (this.length === 0) {
            throw new Error('add at least one temperature value');
        }

        return callback(this.temperatures, this.length);
    }
}

虽然代码确实按预期工作,但有人告诉我,我的代码没有针对空间和时间进行优化,因为随着输入增长到数百万或数十亿温度,用于处理的内存将耗尽,并且还提到了其他一些东西,它需要线性时间 O()。

我对数据结构和算法的了解充其量是非常模糊的,我真的在努力改进这方面的知识。

当我问我可以做些什么来改进代码时,我被告知使用数组以外的东西来存储温度列表,然后让我思考哪个对这个用例最有意义。

在 JavaScript 中可用的数据结构(至少我知道)中,我能想到的只有SetsFloat32Arrays

我能否获得关于哪个更好以及为什么更好的指导,以及如何改进我的解决方案以“优化空间和时间”

标签: javascriptalgorithmdata-structures

解决方案


您不需要任何复杂的数据结构来完成此任务,您只需要跟踪:

  • 迄今为止看到的最高温度
  • 迄今为止看到的最低温度
  • 到目前为止看到的温度总和
  • 到目前为止看到的温度数量

这需要 O(1) 空间,并且每个所述操作都需要 O(1) 时间(要获得平均值,将温度总和除以温度数)。


推荐阅读