Skip to content

Commit

Permalink
数组支持任意位置插入
Browse files Browse the repository at this point in the history
  • Loading branch information
lijialin committed Nov 30, 2018
1 parent e9a0aa3 commit 9c788bd
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions python/05_array/myarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,33 @@ def insert(self, index: int, value: int) -> bool:
self._count += 1
return True

def insert_v2(self, index: int, value: int) -> bool:
"""
支持任意位置插入
:param index:
:param value:
:return:
"""
# 数组空间已满
if self._capacity == self._count:
return False

# 插入位置大于当前的元素个数,可以插入最后的位置
if index >= self._count:
self._data.append(value)
else:
if index < 0:
# 位置小于 0 可以插入第 0 个位置
self._data.insert(0, value)
else:
# 挪动 index 至 _count 位到 index+1 至 _count+1 位
# 插入第 index
self._data[index+1:self._count+1] = self._data[index:self._count]
self._data[index] = value

self._count += 1
return True

def insert_to_tail(self, value: int) -> bool:

if self._count == self._capacity:
Expand Down

0 comments on commit 9c788bd

Please sign in to comment.