數據結構學習筆記——數組

數組的特點

  • 數組中的元素在內存中順序存儲,在邏輯上是順序表
  • 內存是由一個個內存單元組成,每一個內存單元都有自己的地址
  • 數組的初始化後,空間大小固定
  • 數組的下標從0開始

時間複雜度

  • 數組讀取元素的方式爲隨機讀取:array[3],與數組的輸入規模無關,因此時間複雜度爲O(1)
  • 數組的更新元素方式:array[3]=10,與數組的輸入規模無關,時間複雜度O(1);
  • 數組的插入元素,最壞的可能插在數組的頭部,整個數組的下標都要後移1,時間複雜度O(n)
  • 刪除數組的元素,原理同插入元素,時間複雜度爲O(n)

數組demo

package com.cc.array;

public class MyArray {
    private int [] array;
    //數組的實際長度
    private int size;

    public MyArray(int capacity) {
        array=new int[capacity];
        size=0;
    }

    /**
     * 數組插入元素
     * @param index
     * @param element
     * @throws Exception
     */
    public void insert(int index,int element) throws Exception{
        if (index<0||index>size)
            throw new IndexOutOfBoundsException("數組下標越界!");
        //數組的實際長度大於數組容器的長度,對數組進行擴容
        if (size>=array.length)
            resize();
        //從右向左至插入位置,每個元素向右移動一位
        for (int i=size-1;i>=index;i--){
            array[i+1]=array[i];
        }
        //插入位置的元素爲當前插入的元素
        array[index]=element;
        //數組的實際長度加1
        size++;
    }

    /**
     * 實現數組的擴容
     */
    public void resize(){
        //新數組的容器的長度在原來數組容器的長度上*2,實現擴容
        int [] newArray =new int[array.length*2];
        //數組複製,原數組,原數組複製的起位置,目標數組,目標數組的起始位置,複製的長度
        System.arraycopy(array,0,newArray,0,array.length);
        //實現長度擴容
        array=newArray;
    }

    /**
     * 數組輸出
     */
    public void out(){
        for (int i = 0; i <array.length; i++) {
            System.out.println(array[i]);
        }
    }

    /**
     * 刪除指定位置的元素
     * @param index
     * @return
     */
    public int delete(int index){
        if (index<0||index>=size)
            throw new IndexOutOfBoundsException("數組下標越界!");
        int deleteElement =array[index];
        //將後一個元素賦值給錢面一個元素,防止數組越界,i<size-1,因此array[i+1]纔不會越界
        for(int i=index;i<size-1;i++){
            array[i]=array[i+1];
        }
        //將最後一個元素改爲初始值0
        array[size-1]=0;
        //數組的實際長度減一
        size--;
        return deleteElement;
    }

    public static void main(String[] args) throws Exception {
        MyArray myArray =new MyArray(4);
        myArray.insert(0,1);
        myArray.insert(1,2);
        myArray.insert(2,3);
        myArray.insert(3,4);
        myArray.insert(4,25);
//        myArray.out();
        myArray.delete(1);
        myArray.out();

    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章