CodingTour
ARTS #120

Algorithm

本周选择的算法题是:Majority Element

规则

Given an array nums of size n, return the majority element.

The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array.

Example 1:

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

Example 2:

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

Constraints:

  • n == nums.length
  • 1 <= n <= 5 * 104
  • -231 <= nums[i] <= 231 - 1

Follow-up: Could you solve the problem in linear time and in O(1) space?

Solution

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        count, candidate = 0, 0
        for num in nums:
            if count == 0:
                candidate = num
            count += (1 if num == candidate else -1)        
        return candidate

Review

What’s new in Flutter 2.5

很高兴看到 Flutter 在持续完善,2.5 这个版本关闭了 4600 个 issues、3932 个 PRs,比 2.2 多了 6 成,足见 Flutter 团队对社区声音、质量还是挺重视的。

Tip

本周了解到了油猴脚本,通过简单的学习和了解后发现可以解决我们内网 Chrome 插件自动更新的痛点。

Share

分享一配小书《计算机是怎样跑起来的》。

以前看过几本日本人写的书,大致感觉就是严谨加谦虚,这本也不例外,作别是作者解释“哨兵”的故事很生动~

大意是说在某个漆黑的夜晚,要在海岸的悬崖边玩一个游戏,这个游戏的玩法是从悬崖边 100 米开始,每隔 1 米放置一件随机物品,然后看这些随机物品中有没有苹果。如果每走 1 米就检查一下物品是不是苹果,然后再判断有没有到达悬崖边,这两种检查要执行若干次,甚是繁琐。如果采用了哨兵设计,只需要在悬崖边固定放上一个苹果,因为一定可以找到苹果,那么只需要在找到苹果后判断 1 米外是否是悬崖即可,这样的实现就很巧妙。

全书不长,不算深入,适合非科班出身的同学查阅,大约2小时就能看完~