Algorithm
本周选择的算法题是:Sort Colors
规则如下:
Given an array nums
with n
objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.
Here, we will use the integers 0
, 1
, and 2
to represent the color red, white, and blue respectively.
Follow up:
- Could you solve this problem without using the library’s sort function?
- Could you come up with a one-pass algorithm using only
O(1)
constant space?
Example 1:
Input: nums = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
Example 2:
Input: nums = [2,0,1]
Output: [0,1,2]
Example 3:
Input: nums = [0]
Output: [0]
Example 4:
Input: nums = [1]
Output: [1]
Constraints:
n == nums.length
1 <= n <= 300
nums[i]
is0
,1
, or2
.
Solution
这题很简单也很有趣:
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
j, n = 0, len(nums)
for i in range(n):
if nums[i] == 0:
nums[i], nums[j] = nums[j], nums[i]
j += 1
for i in range(j,n):
if nums[i] == 1:
nums[i], nums[j] = nums[j], nums[i]
j += 1
因为值只有固定三个,通过两次循环很直观就能解决,但题目要求了 one-pass
,可以修改如下:
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
i, low, high = 0, 0, len(nums)-1
while i <= high:
if nums[i] == 0:
nums[i], nums[low] = nums[low], nums[i]
i +=1; low += 1
elif nums[i] == 2:
nums[i], nums[high] = nums[high], nums[i]
high -= 1
else:
i += 1
else
的逻辑是一个 edge case 的处理,遇到组合 [1,2,0]
时,2和0交换位置后需要保持 i 当前的值。
Review
文章简洁易读,Web Server 的本质是代理用户和请求资源之间的通信:
- 缓存 - 提高用户获取资源的速度
- 过滤 - 根据地区隐藏资源或者不合适宜的内容
- 负载均衡 - 直接请求到空闲的服务器
- 认证 - 一种鉴权规则
- 日志 - 检测异常之类的情况
- …
早前分享过一张关于HTTP协议版本主要差异的思维导图,这里再重新贴一下:
Tip
一个 Swift Unused Code 检测工具,最近升级到了 2.0 版本:
- 支持 SPM
- 移除了对 SourceKit 的依赖
- 支持 Linux
- 可以很容易集成进已有的 CI 工作流
Share
今天收到了预订的《生财日历-2021》,就是下面这货:
这个日历的名字看起来或许有些“俗”,但其实包含了很多干货。这些干货可以帮你升级赚钱、复制别人的方法,但最重要的是能提升你的认知。
不到30岁,年轻、学习能力强就是最大的资本,相比之下,社会经验不足、对真实的世界缺少客观的感知,没办法把看到的信息和实战经验相关联,是最大的缺陷,对我来说,广度优先的搜索,开眼界、长见识是最重要的。
这个时代不缺少信息,能从身边事物着手,汇聚几十、上百条成功经验的日历无疑是很有性价比的渠道。
了解万事万物的基本运行规律,知道从先人经历中找相似性,能直接快速抽离出事情的本质,用更简单的方法洞察真相,这是我对自己的期望。
我已经迫不及待的想要翻看起来了 :)