ARTS-Week-6

第六周

  • Alogrithm:Container With Most Water
  • Reading:Static Libraries vs. Dynamic Libraries
  • Tech:ELF目标文件与readelf
  • Share:TIMELAPSE OF THE FUTURE: A Journey to the End of Time

Alogrithm

题目—Container With Most Water

Given n non-negative integers a1, a2, …, an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.

Note: You may not slant the container and n is at least 2.
先尝试用暴力解法:

1
2
3
4
5
6
7
8
9
10
int maxArea_force(std::vector<int>& height) {
int max = 0;
for (int i = 0; i < height.size(); ++i) {
for (int j = i + 1; j < height.size(); ++j) {
int area = (height[i] < height[j]) ? height[i] * (j - i) : height[j] * (j - i);
if (area > max) max = area;
}
}
return max;
}

接下来寻找更优的方法想了很久,关键的一点在于想清楚:两边建立两个指针往中间移动过程中,只需要记录最大面积的同时,把相对低的一边往中间移动(这个时候一定是优于移动高的一边),直到这侧的高度大于目前高的一侧。

1
2
3
4
5
6
7
8
9
10
int maxArea(std::vector<int>& height) {
int area = 0, left = 0, right = height.size() - 1, max = 0;
while (left < right) {
int hei = std::min(height[left], height[right]);
max = std::max(max, hei * (right - left));
while (height[left] <= hei && left < right) left++;
while (height[right] <= hei && left < right) right--;
}
return max;
}

Tip:

  • 可直接调用std::maxstd::min求最小最大值。

Reading

针对动态库与静态库的区别,有下面几个文档:

属性 静态库 动态库
链接时间 在编译最后一步被加入进程序中 在链接过程中可执行文件与库被加载到内存之后
调用方式 被链接器链接 由操作系统实现
大小 很大,所有外部程序都被打入了可执行文件中 较小,每一个动态库仅在内存中加载一次
外部文件改变 需重新编译可执行文件 不需要重新编译可执行文件
加载耗时 长,每次执行都需要加载库文件进入内存 短,库代码已经加载在内存中
兼容性 没有兼容性问题,所有代码都在一个可执行文件里 一旦需要的库被从系统里移除就会无法使用

Tech

详细介绍ELF文件格式与readelf工具:ELF目标文件与readelf

Share

推荐一个讲述从2019年到时间尽头是什么样子的延时CG纪录片,4K画质,每一帧画面、每一段配乐都无比精良,解说全是霍金等一众著名科普和物理学大咖。
推荐戴耳机加大屏全屏观看