1.顺序表(ArrayList)
顺序表是一段物理地址连续的存储单元依次存储数据元素的线性结构。除了第一个元素无前驱,最后一个元素无后继,其余元素均有前驱和后继。
2.顺序表接口的实现
public class MyArrayList {
private int[] elem;//用来存放数据元素
private int usedSize;//当前顺序表中有效数据个数
private static final int DEFALUT_SIZE = 2;//默认大小
public MyArrayList(){
this.elem = new int[DEFALUT_SIZE];
}
//指定容量
public MyArrayList(int initCapacity){
this.elem = new int[initCapacity];
}
//打印数组
public void display(){
for (int i = 0; i < this.usedSize; i++) {
System.out.print(this.elem[i] + " ");
}
System.out.println();
}
//新增元素,默认在数组最后新增
public void add(int data){
if(isFull()){
//扩容
this.elem = Arrays.copyOf(this.elem, 2*this.elem.length);
}
this.elem[this.usedSize] = data;
this.usedSize++;
}
//判断数组是否满了
public boolean isFull(){
if(this.usedSize == this.elem.length){
return true;
}
return false;
}
//在pos位置新增元素
public void add(int pos, int data){
if(pos < 0 || pos > this.usedSize){
throw new PosOutBoundException(pos+"位置不合法!");
}
if(isFull()){
//扩容
this.elem = Arrays.copyOf(this.elem, 2*this.elem.length);
}
for (int i = this.usedSize-1; i >= pos ; i--) {
this.elem[i+1] = this.elem[i];
}
this.elem[pos] = data;
this.usedSize++;
}
//判断是否包含某个元素
public boolean contains(int toFind){
for (int i = 0; i < this.usedSize; i++) {
if(this.elem[i] == toFind){
return true;
}
}
return false;
}
//找到某个元素对应的位置
public int indexOf(int toFind){
for (int i = 0; i < this.usedSize; i++) {
if(this.elem[i] == toFind){
return i;
}
}
return -1;
}
//获取pos位置的元素
public int get(int pos){
checkPos(pos);
return this.elem[pos];
}
//给pos位置元素设为value
public void set(int pos,int value){
checkPos(pos);
this.elem[pos] = value;
}
//检查pos位置是否合法
private void checkPos(int pos){
if(pos < 0 || pos >= this.usedSize){
throw new PosOutBoundException(pos +"位置不合法!");
}
}
//删除第一次出现的关键字key
public void remove(int toRemove){
int index = indexOf(toRemove);
if(index == -1){
System.out.println("没有这个数据!");
return;
}
for (int i = index; i < this.usedSize-1; i++) {
this.elem[i] = this.elem[i+1];
}
this.usedSize--;
}
//获取顺序表长度
public int size(){
return this.usedSize;
}
//清空顺序表
public void clear(){
this.usedSize = 0;
}
}
3.顺序表的使用
杨辉三角:每个数是它左上方和右上方的数的和。
class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> ret = new ArrayList<>();
List<Integer> row = new ArrayList<>();
row.add(1);
ret.add(row);
for(int i = 1; i< numRows; i++){
List<Integer> curRow = new ArrayList<>();
curRow.add(1);
List<Integer> prevRow = ret.get(i-1);
for(int j = 1; j < i; j++){
int x = prevRow.get(j) + prevRow.get(j-1);
curRow.add(x);
}
curRow.add(1);
ret.add(curRow);
}
return ret;
}
}
4.顺序表的优缺点
优点:可以快速地存取表中任意位置的元素
缺点:
插入和删除要移动大量元素
顺序表存储结构需要预分配存储空间,分大了浪费,分小了会发生上溢。