Algorithm
本周选择的算法题是:Pairs of Songs With Total Durations Divisible by 60。
规则
You are given a list of songs where the ith
song has a duration of time[i]
seconds.
Return the number of pairs of songs for which their total duration in seconds is divisible by 60
. Formally, we want the number of indices i
, j
such that i < j
with (time[i] + time[j]) % 60 == 0
.
Example 1:
Input: time = [30,20,150,100,40]
Output: 3
Explanation: Three pairs have a total duration divisible by 60:
(time[0] = 30, time[2] = 150): total duration 180
(time[1] = 20, time[3] = 100): total duration 120
(time[1] = 20, time[4] = 40): total duration 60
Example 2:
Input: time = [60,60,60]
Output: 3
Explanation: All three pairs have a total duration of 120, which is divisible by 60.
Constraints:
1 <= time.length <= 6 * 104
1 <= time[i] <= 500
Solution
class Solution:
def numPairsDivisibleBy60(self, time: List[int]) -> int:
ans = 0
# counter = defaultdict(int)
counter = [0] * 60
for item in time:
diff = -item % 60
ans += counter[diff]
counter[item % 60] += 1
return ans
Review
Erik Engheim 的这篇文章和保罗·格雷厄姆在《黑客与画家》里的观点类似,语言是生产工具,但更重要的是,它是生产力工具,这意味着商业竞争的护城河已经延伸到了编程语言的选择上,当你选择比对手生产力更高的编程语言,你就比对手有更大的先发优势。
既然可以使用任何语言,那就不得不思考到底使用哪一种语言。如果你的公司对这种选择的自由视而不见,而竞争对手看到了,那么你就有被击败的危险。语言也能成为商业、技术的杠杆。
Tip
学习了 Kafka 时间轮(TimingWheel)算法,真是一个精妙的算法,三层时间轮用60个数组元素(wheelSize=20)就可以承载[0-7999]个定时任务!
Share
最近在做业务跨端的规划,动作拆解为:
- 确定具体的页面后,先用原生技术优化到足够好 ⬅️ 价值体现:让用户得到最实在的体验收益
- 再用 Kotlin Native + 原生 UI 和纯原生做性能对比 ⬅️ 验证价值:不重写 UI 代码的情况下,KN 方案落地成本低,作为兜低方案,可以统一移动端一半左右的代码量
- 再用 Kotlin Native + Flutter UI 和前述方案做对比 ⬅️ 验证价值:业务代码不重写的情况下,验证 UI 性能、体验是否达到预期
- 最后用 Dart + Flutter UI 做跨端技术栈的最终价值验证