CodingTour
ARTS #79

Algorithm

本周选择的算法题是:Swap Nodes in Pairs

规则如下:

Given a linked list, swap every two adjacent nodes and return its head.

You may not modify the values in the list’s nodes. Only nodes itself may be changed.

Example 1:

Input: head = [1,2,3,4]
Output: [2,1,4,3]

Example 2:

Input: head = []
Output: []

Example 3:

Input: head = [1]
Output: [1]

Constraints:

  • The number of nodes in the list is in the range [0, 100].
  • 0 <= Node.val <= 100

Solution

class Solution:
    def swapPairs(self, head: ListNode) -> ListNode:
        fake = ListNode(next=head)
        temp = fake
        while temp.next and temp.next.next:
            next = temp.next.next.next
            temp.next, temp.next.next, temp.next.next.next = temp.next.next, temp.next, next
            temp = temp.next.next

        return fake.next

这类单向链表有几个公共策略:

  • 因为要返回 head,往往需要一个 fake or dummy 头用于定位
  • 用单指针或双指针遍历

Review

The Most Elegant Python Object-Oriented Programming

这篇文章介绍了 Marshmallow 基本用法和高级特性,目的是为了在 Python 里实现最优雅的 OOP。

Python 原本是一门弱类型+动态类型的语言,现在社区里却有一种趋势,通过拓展实现了比一些原生强类型的语言更强大的 OOP 特性。不管是 Marshmallow 还是可能更流行的 Pydantic,它们的功能包括并不限于:

  • 类型标注
  • 类型检查
  • 类型值验证、默认值
  • 属性别名
  • 序列化和反序列化

这从语言的发展来说是一件好事,可以看出:

  • 语言具有极强的灵活性
  • 是活跃的,越来越多人在使用它,社区在不断发展
  • 适用领域更广了

原生强类型的语言也能从中得到一些灵感。

Tip

另一个打卡社区:Advent of Code,编程难度更有挑战,每天有不同的问题,分为简单版的 Part1 和困难版的 Part2。

Share

分享一篇在 CocoaPods 中应用 symlink 的实践:Symlinks on CocoaPods