CodingTour
ARTS #101

Algorithm

本周选择的算法题是:Single Number

规则

Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.

Follow up: Could you implement a solution with a linear runtime complexity and without using extra memory?

Example 1:

Input: nums = [2,2,1]
Output: 1

Example 2:

Input: nums = [4,1,2,1,2]
Output: 4

Example 3:

Input: nums = [1]
Output: 1

Constraints:

  • 1 <= nums.length <= 3 * 104
  • -3 * 104 <= nums[i] <= 3 * 104
  • Each element in the array appears twice except for one element which appears only once.

Solution

很经典的一道题,XOR 的解法:

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        ans = 0
        for num in nums:
            ans ^= num
        return ans

数学解法:

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        return 2 * sum(set(nums)) - sum(nums)

Review

Basics of Microservice Architecture

这篇文章比较全面的介绍了微服务架构的优缺点和其所包含的设计模式。文章首先从 Monolith 开始,经过 Hexagonal、CI/CD、Scale Cube 等阶段到达 Microservice architecture,期间穿插介绍了各个阶段的优缺点,让读者体验了一把架构升级之路,文章配图较多,但图片的质量很高,比如用一张图很优雅的解释清了 Continuous Deployment 和 Continuous Delivery 之间的区别:

img

Continuous Deployment V/S Continuous Delivery

虽然 MSA 是面向后端的架构,但设计模式是通用的,总体上值得一看。

Tip

@classmethod vs @staticmethod vs “plain”:

class MyClass:
    def method(self):
        """
        Instance methods need a class instance and
        can access the instance through `self`.
        """
        return 'instance method called', self

    @classmethod
    def classmethod(cls):
        """
        Class methods don't need a class instance.
        They can't access the instance (self) but
        they have access to the class itself via `cls`.
        """
        return 'class method called', cls

    @staticmethod
    def staticmethod():
        """
        Static methods don't have access to `cls` or `self`.
        They work like regular functions but belong to
        the class's namespace.
        """
        return 'static method called'

Share

坦诚让管理变得更简单