Algorithm
本周选择的算法题是:Sqrt(x)
规则如下:
Implement int sqrt(int x)
.
Compute and return the square root of x, where x is guaranteed to be a non-negative integer.
Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.
Example 1:
Input: 4
Output: 2
Example 2:
Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since
the decimal part is truncated, 2 is returned.
Solution
Runtime:40 ms,快过 37.93%。
Memory:13.7 MB,低于 6.45%。
class Solution:
def mySqrt(self, x: int) -> int:
left, right = 1, x
while left <= right:
num = (left + right) // 2
square = num * num
if square == x:
return num
elif square > x:
right = num - 1
else:
left = num + 1
return right
附牛顿迭代法:
class Solution:
def mySqrt(self, x: int) -> int:
r = x
while r*r > x:
r = int((r + x/r) // 2)
return r
Review
Xcode Build Time Optimization - Part 2 接上周的文章。
上篇文章主要是测量/评估 Xcode 的编译时长,这篇则是如何解决具体的问题。
这些问题可以分为以下几个方面:
- 编译设置
- Build Active Architecture Only (ONLY_ACTIVE_ARCH)
- Compilation Mode (SWIFT_COMPILATION_MODE) -
DEBUG
下设置为Incremental
,Release
下设为Whole Module
- Optimization Level (SWIFT_OPTIMIZATION_LEVEL)
- Debug Information Format (DEBUG_INFORMATION_FORMAT) -
dSYM
是一个符号表调试文件,Debug 环境下不需要
- 源码改进
- 借助工具找出代码中编译慢的部分
- 减少 rebuild - 降低文件之间的依赖关系
- 删除不需要的代码
- 预编译依赖文件 - 制作成动态库,适合更新不频繁的场景
- Code or Xibs/Storyboards - 后者对编译时长、包大小影响更大,但影响也有限
- 工程管理
- 改善 Run Script
- 考虑能否延后执行,比如延迟到 git commit
- 考虑能否针对
Debug
环境或者模拟器环境跳过执行
- 适配模块化的架构
- 减少模块之前的依赖将有助于 Xcode 进行并行编译
- 改善 Run Script
- 其他
- 引入
Buck
orBazel
这样的外部工具
- 引入
Tip
在 Python Subprocess 中捕获 output 的同时实时输出:
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
while process.poll() is None:
output = process.stdout.readline()
if output:
print(output.decode('utf-8').strip())
Share
《圆桌派》嘉宾许子东分享过一个成就感公式:成就感 = 你的能力 / 你的理想——如果设定的理想是200分,能力却只有10分,那成就感就只剩0.5了,过大的目标只会带来挫败感,而非成就感。
持续收获成就感比目标更重要。