数组中根据给定索引插入值,给定索引之后的元素都需要后移一位。
两种情况,需要考虑:
1、给定索引为负数,将其放在首位。
2、给定索引超出数组长度,将其放在末位。
Python实现
python支持负索引和值为None的元素,情况复杂一点.,代码如下。
class Array(object):
def __init__(self, lst):
self.size = len(lst)
self.lst = lst
def insert(self, index, e):
count_None = 0 #记录数组中None值得数量
if index < 0:
if (-index) > self.size:
index = 0 #索引为负数且绝对值大于数组长度,将其置于首位
else:
index = index + self.size
if index > self.size: #索引是正数且值大于数组长度,将其置于末位
index = self.size
#None值判断与优化
if self.lst[index] is None: #index位置为None,直接插入值
self.lst[index] = e
return self.lst
else: #index位置不为None,记录数组中None得数量
for i in range(self.size - 1, index, -1):
if self.lst[i] is None:
count_None += 1
#没有None值,数组扩容
if count_None == 0:
self.resize(2)
#插入数据
for i in range(self.size - 2, index - 1, -1):
if (self.lst[i] is not None) and (self.lst[i + 1] is None):
self.lst[i + 1] = self.lst[i]
self.lst[i] = None
self.lst[index] = e
def resize(self, multiple: int):
'''
扩容数组
:param multiple:扩容倍数
'''
self.size = self.size * multiple
lst_new = [None for i in range(self.size)]
for i in range(len(self.lst)):
lst_new[i] = self.lst[i]
self.lst = lst_new.copy()
if __name__ == '__main__':
list = [1, 2, 3, 4, 1, 2, 2, 4]
print(list)
array = Array(list)
array.insert(2, 8)
print(array.lst)
Java实现
public int[] ArrayInsert(int[] array, int index, int value) {
int n = array.length;
//数组扩容
int[] array_new = new int[n + 1];
int index_new = index;
//负数的索引,放于首位
if (index <= 0) {
index_new = 0;
}
//超出数组长度的索引,默认置于末位
if (index >= n) {
index_new = n;
}
//获取索引之前的数据
for (int i = 0; i < index_new; i++) {
array_new[i] = array[i];
}
//获取索引之后的数据
for (int i = index_new; i < n; i++) {
array_new[i + 1] = array[i];
}
array_new[index_new] = value;
return array_new;
}