# 数据结构学习之线性表（二）

1. 首先我们定义的数组类型 不支持泛型。

2. 当容量不够使用的时候, 应该可以自动触发扩容操作。

public class Array<T>
{
private T[] Data;
private int Size;
private int Capacity;
public bool IsFull => this.Capacity == this.Size;
public Array(int capacity = 20)
{
this.Capacity = capacity;
this.Data = new T[this.Capacity];
}
}

public void Add(T value)
{
if (IsFull)
this.ExpandCapacity(this.Capacity * 2);
this.Size++;
this.Data[this.Size - 1] = value;
}
}
private void ExpandCapacity(int capacity)
{
var newData = new T[capacity];
for (int i = 0; i < newData.Length; i++)
{
newData[i] = this.Data[i];
}
this.Data = newData;
this.Capacity = capacity;
}

public T Delete(int index)
{
if (index < 0)
throw new Exception("index is less than zero");
if (index > this.Capacity-1)
throw new Exception("index is more than capacity");
if (index > this.Size-1)
return default;
var value = this.Data[index];
for (int i = index; i < this.Size-1; i++)
{
this.Data[i] = this.Data[i+1];
}
this.SetEmpty(this.Size-1);
this.Size--;
if (this.Size <= this.Capacity/2)
this.NarrowCapacity(this.Capacity / 2);
return value;
}

private void NarrowCapacity(int capacity)
{
var newData = new T[capacity];
for (int i = 0; i < this.Data.Length; i++)
{
newData[i] = this.Data[i];
}
this.Data = newData;
this.Capacity = capacity;
}

public bool IsContain(int value)
{
var isContain = false;
for (int i = 0; i < this.Size; i++)
{
if (this.Data[i].Equals(value))
isContain = true;
}
return isContain;
}

1.增加 O(1) 这个没什么好说 ，但如果已满，触发了扩容复杂度为 O(n)。

2.插入  插入的话，如果插入的index为Size ,此时的复杂度为 O(1) ,但最坏情况下为插入到第一个,此时的复杂度为 O(n),平均复杂度为(n/2),还是 O(n)

3.删除 删除也是一样。也会有最坏情况,复杂度为 O(n).

4.查找 O(1)

if (this.Size <= this.Capacity/4)
this.NarrowCapacity(this.Capacity / 2);

posted @ 2019-06-16 22:35  MUYIgUAN  阅读(145)  评论(0编辑  收藏