ARTS-week29

Algorithms

Contains Duplicate
思路:遍历数组,使用哈希。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
unordered_set<int> hash;
int n = nums.size();
for (int i = 0; i < n; ++i) {
if (hash.find(nums[i]) != hash.end()) {
return true;
}
hash.insert(nums[i]);
}
return false;
}
};

Contains Duplicate II

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
unordered_map<int, int> hash;
int n = nums.size();
for (int i = 0; i < n; ++i) {
if (hash.find(nums[i]) != hash.end() && i - hash[nums[i]] <= k) {
return true;
} else {
hash[nums[i]] = i;
}
}
return false;
}
};

Review

本周阅读英文文章 Passwordless SMS Authentication: The Basics

Technique

Python标准库中有两个剖析模块:profile和cProfile,profile完全使用Python编写,给程序执行增加了很大的开销。cProfile的接口与profile相同,使用C语言编写,开销小,适合用作剖析器,但cProfile只提供函数级信息,而不会指出导致瓶颈的具体是哪些语句。

cProfile的三种不同使用方式:
1)命令行;
按照执行函数花费的总时间对输出进行排序

1
python -m cProfile -s tottime app.py

2)作为Python模块使用;

1
2
3
4
from app import datapull
import cProfile

cProfile.run("datapull()")

3)在IPython中使用。

1
2
3
In[1]: from app import datapull

In[2]: %prun datapull()

可以使用pyprof2-calltree和KCachegrind对cProfile的输出文件进行可视化。

Share

在腾讯应急安全响应中心的博客中看到一篇从安全角度看超长函数的文章: 拒绝超长函数,从两个curl远程漏洞说起

因为函数的栈帧中有太多的局部变量,一旦某个变量发生缓冲区溢出,或者其他什么变量发生了Out of bounds存取,极有可能会影响到其他局部变量的值。而如果把函数分成很多小函数,即使发生了栈缓冲区溢出,因为有Stack cookie的保护,攻击者也不太可能会直接影响到其他函数中的栈帧(因为在调用到那里前就会因为cookie不符合程序直接崩溃)。

0%