Python中的11 种数组算法
1. 创建数组
创建数组意味着留出一个连续的内存块来存储相同类型的元素。在大多数语言中,您可以在创建数组时指定数组的大小。
假设您正在书架上整理一组书籍,并且您需要为正好 10 本书预留空间。功能架上的每个空间都对应于数组中的一个索引。
# Example in Python
arr = [1, 2, 3, 4, 5] # Creates an array with 5 elements
2. 遍历数组
To iterate 表示逐个访问数组中的每个元素。此操作是许多算法的基础。
考虑在商店中移动时,将购物清单中的项目一一核对。遍历数组就像遍历该列表。
# Example in Python
for item in arr:
print(item) # Prints each element in the array
3. 获取元素
从数组中检索元素意味着访问特定索引处的项目。
如果您的书籍是按字母顺序排列的,如果您知道它的索引,您可以快速转到书架上的第三本书。
# Example in Python
print(arr[2]) # Access the third element in the array (index starts at 0)
4. 搜索元素
搜索包括查找数组中是否存在给定元素,如果存在,则标识其位置。
如果要在图书馆中查找特定书籍,则搜索数组就像扫描书架直到找到该书籍一样。
# Example in Python
target = 4
if target in arr:
print(f"Found {target} at index {arr.index(target)}")
else:
print(f"{target} not found")
5. 插入元素
插入意味着向数组添加新元素。这可能是在结尾、开头或介于两者之间的某个位置。
想象一下,将一本新书放在书架上。如果你想把它插入中间,就必须移动其他的书来腾出空间。
# Example in Python
arr.append(6) # Adds an element at the end
arr.insert(2, 10) # Inserts 10 at index 2
6. 删除元素
删除涉及从数组中删除元素并移动剩余元素以填充间隙。
如果您从书架上拿下一本书,其他书籍可能会滑过来填补空白空间。
# Example in Python
arr.remove(3) # Removes the element with value 3
del arr[1] # Removes the element at index 1
7. 过滤数组
筛选意味着创建一个仅包含满足特定条件的元素的新数组。
假设您有一个书籍集合,并且您只想查找特定作者的书籍。筛选通过根据条件选择项目来帮助您实现此目的。
# Example in Python
filtered_arr = [x for x in arr if x > 2] # Filters elements greater than 2
8. 获取子数组
获取子数组意味着提取数组的一部分,就像取出它的一个切片一样。
考虑从一本书中选择几页进行评论。你没有拿走整本书,只是一小部分。
# Example in Python
sub_arr = arr[1:4] # Extracts elements from index 1 to 3
9. 合并数组
合并会将两个或多个数组合并为一个数组。
合并数组就像将两组人合并到一个团队中。它们不是单独的实体,而是作为一个统一的组一起工作。
# Example in Python
arr2 = [7, 8, 9]
merged_arr = arr + arr2 # Combines both arrays
10. 反转数组
反转数组意味着颠倒它的顺序,所以第一个元素变成最后一个元素,反之亦然。
这就像把一副牌倒过来——上面的最后一张牌现在在底部,而下面的牌现在在上面。
# Example in Python
arr.reverse() # Reverses the order of the array
11. 旋转数组
旋转数组会将其所有元素移动一定数量的位置。从末尾移出的元素将环绕到开头。
想象一下一排人在旋转。前面的人向后移动,而其他人向前移动。
# Example in Python
n = 2
rotated_arr = arr[-n:] + arr[:-n] # Rotates the array by 2 positions