【问题标题】:sum of complexity复杂度总和
【发布时间】:2020-04-18 13:07:22
【问题描述】:

假设你得到了

A=[2, 5, 7, 2, 6, 7, 6, 5, 6, 5].  

Sum=[0, 0, 0, 12, 0, 8, 7, 28, 5, 6].

使用 O(n) 额外空间并且**必须在 O(n) 时间内运行****。


【问题讨论】:

  • unordered_map 应该可以工作。与其保存最后一次出现相同数字的索引,不如尝试保存前缀总和直到该元素。
  • “但我认为没有可以直接在 C++ 中动态创建和访问其索引的数据结构”std::vector 允许随机访问。
  • @Jarod42 感谢您的关注,我意识到 :)

标签: c++ arrays data-structures time-complexity


【解决方案1】:

如果你被允许使用std::unordered_map,你可以使用类似的东西:

auto IntervalSum(const std::vector<int>& A)
{
    std::vector<int> res;
    std::unordered_map<int, int> m;
    int sum = 0;

    for (auto e : A) {
        sum += e;
        if (auto [it, inserted] = m.emplace(e, sum); !inserted) {
            res.push_back(sum - e - it->second);
            it->second = sum;
        } else {
            res.push_back(0);
        }
    }
    return res;
}

Demo

C++17 构造

if (auto [it, inserted] = m.emplace(e, sum); !inserted) {

可能在以前的版本(C++11/C++14)中被重写:

auto p = m.emplace(e, sum);
auto it = p.first;
bool inserted = p.second;
if (!inserted) {

【讨论】:

  • 当我尝试使用 vs 2019“标识符“it”未定义”时,我也无法理解 auto [it, inserted] 部分。
  • 该行使用 2 个 C++17 特性:structured_binding:emplace 返回一个 pair&lt;iterator, bool&gt;,迭代器部分是 itbool 部分是 inserted。以及在if 中声明的可能性。
猜你喜欢
  • 1970-01-01
  • 2012-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-12
  • 2021-11-14
  • 1970-01-01
相关资源
最近更新 更多