【问题标题】:why Binary Operator gives TLE while compound assignment operator is faster?为什么二元运算符给出 TLE 而复合赋值运算符更快?
【发布时间】:2021-11-20 15:40:53
【问题描述】:

我正在尝试解决 LeetCode 上的Sort Characters By Frequency。第一个使用的二元运算符给了我一个 TLE,但是当我使用复合赋值运算符时它工作正常。但我不明白为什么。

这背后有什么逻辑吗?我在下面附上了两个代码,您可以自己尝试一下。

这给了 TLE

class Solution {
public:
    string frequencySort(string s) {
        
        unordered_map<char, int> m;
        for(int i = 0; i < s.length(); i++)
            m[s[i]]++;
        
        priority_queue<pair<int, char>> pq; // maxheap based on frequency
        for(auto x = m.begin(); x != m.end(); x++)
            pq.push(make_pair(x->second, x->first));
        
        string ans = "";
        while (!pq.empty())
        {
            for(int i = 0; i < pq.top().first; i++)
                ans = ans + pq.top().second;
            pq.pop();
        }
        
        return ans;
    }
};

这很好用

class Solution {
public:
    string frequencySort(string s) {
        
        unordered_map<char, int> m;
        for(int i = 0; i < s.length(); i++)
            m[s[i]]++;
        
        priority_queue<pair<int, char>> pq; // maxheap based on frequency
        for(auto x = m.begin(); x != m.end(); x++)
            pq.push(make_pair(x->second, x->first));
        
        string ans = "";
        while (!pq.empty())
        {
            for(int i = 0; i < pq.top().first; i++)
                ans += pq.top().second;
            pq.pop();
        }
        
        return ans;
    }
};

【问题讨论】:

    标签: c++ operators binary-operators compound-assignment


    【解决方案1】:

    ans = ans + pq.top().second; 创建一个临时字符串,然后将其移动到ans。除非应用小字符串优化,否则每个操作都涉及内存分配和解除分配。

    ans += pq.top().second; 不会创建临时内存,只有在ans 先前保留的内存用完时才会分配内存 - 这种情况发生的频率要低得多。

    【讨论】:

      猜你喜欢
      • 2011-11-16
      • 2013-11-26
      • 2020-12-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-28
      • 1970-01-01
      • 2015-12-14
      • 1970-01-01
      相关资源
      最近更新 更多