From 9c788bde5458ead84dc5f9b0063202c7f2915ef2 Mon Sep 17 00:00:00 2001 From: lijialin Date: Fri, 30 Nov 2018 14:43:31 +0800 Subject: [PATCH] =?UTF-8?q?=E6=95=B0=E7=BB=84=E6=94=AF=E6=8C=81=E4=BB=BB?= =?UTF-8?q?=E6=84=8F=E4=BD=8D=E7=BD=AE=E6=8F=92=E5=85=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- python/05_array/myarray.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/python/05_array/myarray.py b/python/05_array/myarray.py index 03a07ec..547e3b5 100644 --- a/python/05_array/myarray.py +++ b/python/05_array/myarray.py @@ -59,6 +59,33 @@ class MyArray: 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: