Skip to content

Commit dbe8801

Browse files
Merge pull request #172 from FoolLea/master
数组 insert 函数不支持任意位置插入
2 parents 289e63e + 05fb591 commit dbe8801

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

python/05_array/myarray.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,32 @@ def insert(self, index: int, value: int) -> bool:
5959
self._count += 1
6060
return True
6161

62+
def insert_v2(self, index: int, value: int) -> bool:
63+
"""
64+
支持任意位置插入
65+
:param index:
66+
:param value:
67+
:return:
68+
"""
69+
# 数组空间已满
70+
if self._capacity == self._count:
71+
return False
72+
73+
# 插入位置大于当前的元素个数,可以插入最后的位置
74+
if index >= self._count:
75+
self._data.append(value)
76+
elif index < 0:
77+
# 位置小于 0 可以插入第 0 个位置
78+
self._data.insert(0, value)
79+
else:
80+
# 挪动 index 至 _count 位到 index+1 至 _count+1 位
81+
# 插入第 index
82+
self._data[index+1:self._count+1] = self._data[index:self._count]
83+
self._data[index] = value
84+
85+
self._count += 1
86+
return True
87+
6288
def insert_to_tail(self, value: int) -> bool:
6389

6490
if self._count == self._capacity:

0 commit comments

Comments
 (0)