Add Swift language blocks to the docs.

This commit is contained in:
Yudong Jin
2023-01-08 19:41:05 +08:00
parent 3ba37dba3a
commit 73e3452838
22 changed files with 414 additions and 70 deletions
+43
View File
@@ -91,6 +91,12 @@ comments: true
List<int> list = numbers.ToList();
```
=== "Swift"
```swift title="list.swift"
```
**访问与更新元素**。列表的底层数据结构是数组,因此可以在 $O(1)$ 时间内访问与更新元素,效率很高。
=== "Java"
@@ -169,6 +175,12 @@ comments: true
list[1] = 0; // 将索引 1 处的元素更新为 0
```
=== "Swift"
```swift title="list.swift"
```
**在列表中添加、插入、删除元素**。相对于数组,列表可以自由地添加与删除元素。在列表尾部添加元素的时间复杂度为 $O(1)$ ,但是插入与删除元素的效率仍与数组一样低,时间复杂度为 $O(N)$ 。
=== "Java"
@@ -317,6 +329,12 @@ comments: true
list.RemoveAt(3);
```
=== "Swift"
```swift title="list.swift"
```
**遍历列表**。与数组一样,列表可以使用索引遍历,也可以使用 `for-each` 直接遍历。
=== "Java"
@@ -437,6 +455,12 @@ comments: true
}
```
=== "Swift"
```swift title="list.swift"
```
**拼接两个列表**。再创建一个新列表 `list1` ,我们可以将其中一个列表拼接到另一个的尾部。
=== "Java"
@@ -502,6 +526,12 @@ comments: true
list.AddRange(list1); // 将列表 list1 拼接到 list 之后
```
=== "Swift"
```swift title="list.swift"
```
**排序列表**。排序也是常用的方法之一,完成列表排序后,我们就可以使用在数组类算法题中经常考察的「二分查找」和「双指针」算法了。
=== "Java"
@@ -559,6 +589,12 @@ comments: true
list.Sort(); // 排序后,列表元素从小到大排列
```
=== "Swift"
```swift title="list.swift"
```
## 列表简易实现 *
为了帮助加深对列表的理解,我们在此提供一个列表的简易版本的实现。需要关注三个核心点:
@@ -1220,3 +1256,10 @@ comments: true
}
}
```
=== "Swift"
```swift title="my_list.swift"
```