CodingTour
ARTS #142

Algorithm

本周选择的算法题是:Remove K Digits

规则

Given string num representing a non-negative integer num, and an integer k, return the smallest possible integer after removing k digits from num.

Example 1:

Input: num = "1432219", k = 3
Output: "1219"
Explanation: Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest.

Example 2:

Input: num = "10200", k = 1
Output: "200"
Explanation: Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes.

Example 3:

Input: num = "10", k = 2
Output: "0"
Explanation: Remove all the digits from the number and it is left with nothing which is 0.

Constraints:

  • 1 <= k <= num.length <= 105
  • num consists of only digits.
  • num does not have any leading zeros except for the zero itself.

Solution

class Solution:
    def removeKdigits(self, num: str, k: int) -> str:
        if k >= len(num): return "0"
        
        stack = []
        for item in num:
            while k and stack and stack[-1] > item:
                stack.pop()
                k -= 1
            if stack or item != '0':
                stack.append(item)
        while stack and k > 0:
            stack.pop()
            k -= 1
        
        return "0" if not stack else "".join(stack)

Review

Caching — System Design Concept

文章以介绍缓存的整体概念为主,如淘汰策略:RR、LFU、LRU、FIFO,在业界的应用场景:应用服务器缓存、CDN、CS 缓存、ISP 缓存等,还有读写策略:Write through、Write around、Write back 等,内容不深,适合初学者。

缓存系统的每个环节展开后都不简单,就拿淘汰策略来说,文中提到的策略满足不了全部场景,更复杂的算法还有像 IBM Almaden 研究中心开发的,能同时跟踪记录 LFU 和 LRU 的 ARC(Adaptive Replacement Cache)算法,能通过对读取、淘汰行为的识别,自适应当前的 I/O 模式。

Wiki 中有记录更多淘汰策略:Cache replacement policies

Tip

  • 学习了 JumpServer 的使用
  • 通过在 DevOps 流程中引入 cnpm 将内部前端项目的部署从 15mins 降低到了 4mins

Share

分享一个纯 JS & HTML 实现的 loading 效果:

代码如下:

const loadProgressMapper = [
  "▯▯▯▯▯▯▯▯▯▯",
  "▮▯▯▯▯▯▯▯▯▯",
  "▮▮▯▯▯▯▯▯▯▯",
  "▮▮▮▯▯▯▯▯▯▯",
  "▮▮▮▮▯▯▯▯▯▯",
  "▮▮▮▮▮▯▯▯▯▯",
  "▮▮▮▮▮▮▯▯▯▯",
  "▮▮▮▮▮▮▮▯▯▯",
  "▮▮▮▮▮▮▮▮▯▯",
  "▮▮▮▮▮▮▮▮▮▯",
  "▮▮▮▮▮▮▮▮▮▮"
];
const suffix = 'LOADING…';
var loadingBar = document.getElementById('loadingBar');
var counter = 0;
var toContinueLoading = setInterval( () => {
 var toDisplay = `${loadProgressMapper[counter++]} ${suffix}`;
 loadingBar.innerHTML = toDisplay;
 if (counter === loadProgressMapper.length) {
  counter = 0;
 }
}, 200);

此前我在博客性能优化中引入过用纯 CSS 实现的 loading 效果,也挺 trick 的~