C++刷leetcode几点注意事项

  1. size() 返回的无符号数

大概的场景如下:

int maxLen = -1
if(s.size() > maxLen) {
    maxLen = s.size();
}

由于有符号数和无符号数比较时,会当做无符号数比较,所以-1是 \(2^{31}-1\)
所以记得加上强制类型转换

  1. string类型参数,未修改是记得加引用

例如Leetcode 472. 连接词,未加引用会超时,而加上引用就176ms过

int query(Node* p, string& str, int pos) {    // 记得加引用

因为这题中,最多有1e5个字符串,每个字符串可能调用size次query,所有大量的拷贝会导致超时

  1. 统计是否出现而不是次数是,尽量用unordered_set
    unordered_map比unordered_set慢,

例如 Leetcode 面试题 17.13. 恢复空格,用unordered_map花了1040ms,而unordered_set只用了204ms

  1. vector的resize可能会导致超时
vector<int>hs;
hs.resize(n);

or

vector<int> hs[n];   

例如我在Leetcode 336回文对中的提交 https://leetcode-cn.com/submissions/detail/252119270/,前者会超时,后者不会
cpprefence中关于vector resize的复杂度描述:

Complexity
Linear in the difference between the current size and count. Additional complexity possible due to reallocation if capacity is less than count

  1. string的size()函数虽然是常数时间,但是也需要尽量少调用

同样在Leetcode 336中,
正常写法:https://leetcode-cn.com/submissions/detail/252119613/,1036 ms
减少size调用:https://leetcode-cn.com/submissions/detail/252119899/,568 ms
cpprefence说的是 Constant(since C++11)

posted @ 2021-12-25 21:49  Rogn  阅读(131)  评论(0编辑  收藏  举报