CodingTour
ARTS #107

Algorithm

本周选择的算法题是:4Sum II

规则

Given four integer arrays nums1, nums2, nums3, and nums4 all of length n, return the number of tuples (i, j, k, l) such that:

  • 0 <= i, j, k, l < n
  • nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0

Example 1:

Input: nums1 = [1,2], nums2 = [-2,-1], nums3 = [-1,2], nums4 = [0,2]
Output: 2
Explanation:
The two tuples are:
1. (0, 0, 0, 1) -> nums1[0] + nums2[0] + nums3[0] + nums4[1] = 1 + (-2) + (-1) + 2 = 0
2. (1, 1, 0, 0) -> nums1[1] + nums2[1] + nums3[0] + nums4[0] = 2 + (-1) + (-1) + 0 = 0

Example 2:

Input: nums1 = [0], nums2 = [0], nums3 = [0], nums4 = [0]
Output: 1

Constraints:

  • n == nums1.length
  • n == nums2.length
  • n == nums3.length
  • n == nums4.length
  • 1 <= n <= 200
  • -228 <= nums1[i], nums2[i], nums3[i], nums4[i] <= 228

Solution

class Solution:
    def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
        table = dict()
        for i in nums1:
            for j in nums2:
                table[i+j] = table.get(i+j, 0) + 1

        ans = sum(table.get(-l-k, 0)for k in nums4 for l in nums3)
        return ans

Review

How to use Consistent Hashing in a System Design Interview?

本文详述了一致性哈希算法的原理以及在系统中的应用方式,包括数据分片、数据复制和虚拟节点的作用和优势。一致性哈希算法由于解决了简单哈希算法在分布式哈希表中存在动态伸缩的问题,使数据迁移的成本变得很低,在分布式系统中应用广泛,是非常经典的算法。

本文对于想要了解这部分概念的同学很有帮助。

Tip

Python 中有两个有趣的函数:

  • globals - returns a dict with all global variables in the current scope
  • locals - does the same but for all local variables in the current scope

Share

移动端 CI & CD 全流程一览