1. 程式人生 > >玩轉資料結構入門與進階——第一章:陣列

玩轉資料結構入門與進階——第一章:陣列

內容大綱:

  1. 使用Java中的陣列
  2. 二次封裝屬於我們自己的陣列
  3. 向陣列中新增元素
  4. 陣列中查詢元素和修改元素
  5. 包含,搜尋,刪除功能
  6. 使用泛型
  7. 動態陣列
  8. 簡單的時間複雜度分析
  9. 均攤複雜度和防止複雜度振盪

一、java中的陣列

  • 把資料碼成一排進行存放

java中一個簡單的陣列使用

public class Main {

    public static void main(String[] args) {

        int[] arr = new int[10];
        for(int i = 0 ; i < arr.length ; i ++)
            arr[i] = i;

        int[] scores = new int[]{100, 99, 66};
        for(int i = 0 ; i < scores.length ; i ++)
            System.out.println(scores[i]);

        for(int score: scores)
            System.out.println(score);

        scores[0] = 96;

        for(int i = 0 ; i < scores.length ; i ++)
            System.out.println(scores[i]);
    }
}

二、二次封裝屬於我們自己的陣列

  • 陣列的最大優點:快搜查詢,score[2];
  • 陣列最好應用於"索引有語意"的情況
  • 但並非所有有語意的索引都適合用於陣列  例如身份證號碼

1、製作屬於我們自己的陣列類

public class Array {

    private int[] data;
    private int size;

    // 建構函式,傳入陣列的容量capacity構造Array
    public Array(int capacity){
        data = new int[capacity];
        size = 0;
    }

    // 無引數的建構函式,預設陣列的容量capacity=10
    public Array(){
        this(10);
    }

    // 獲取陣列的容量
    public int getCapacity(){
        return data.length;
    }

    // 獲取陣列中的元素個數
    public int getSize(){
        return size;
    }

    // 返回陣列是否為空
    public boolean isEmpty(){
        return size == 0;
    }
}

三、向陣列中新增元素

在陣列末尾新增元素

    // 向所有元素後新增一個新元素
    public void addLast(int e){
       if(size == data.length)
           throw new IllegalArgumentException("AddLast failed. Array is full.");

        data[size] = e;
        size ++;
        add(size, e);
    }

在指定位置新增元素

    // 在index索引的位置插入一個新元素e
    public void add(int index, int e){

        if(size == data.length)
            throw new IllegalArgumentException("Add failed. Array is full.");

        if(index < 0 || index > size)
            throw new IllegalArgumentException("Add failed. Require index >= 0 and index <= size.");

        for(int i = size - 1; i >= index ; i --)
            data[i + 1] = data[i];

        data[index] = e;

        size ++;
    }

在陣列頭部新增一個元素和在陣列末尾新增一個元素都可以改為

// 在所有元素末尾新增一個新元素  
 public void addLast(int e){

        add(size, e);
    }
    // 在所有元素前新增一個新元素
    public void addFirst(int e){
        add(0, e);
    }

四、陣列中查詢元素和修改元素

重寫父類toString()方法:返回此時陣列的元素個數size和容量capacity

    @Override
    public String toString(){
        StringBuilder res=new StringBuilder();
        res.append(String.format("Array: size=%d, capacity=%d\n",size,data.length));
        res.append('[');
        for(int i=0;i<size;i++){
            res.append(data[i]);
            if(i!=size-1)//如果沒到末尾
                res.append(",");//拼接一個","
        }
        res.append(']');
        return res.toString();
    }

查詢陣列中某個位置的元素

    // 獲取index索引位置的元素
    public int get(int index){
        if(index < 0 || index >= size)
            throw new IllegalArgumentException("Get failed. Index is illegal.");
        return data[index];
    }

修改陣列某個位置的元素


    // 修改index索引位置的元素為e
    public void set(int index, int e){
        if(index < 0 || index >= size)
            throw new IllegalArgumentException("Set failed. Index is illegal.");
        data[index] = e;
    }

五、包含,搜尋,刪除功能

陣列中是否包含有此元素

  //查詢是否有元素e
    public boolean contain(int e){
        for(int i=0;i<size;i++){
            if(data[i]==e)
                return true;
        }
        return false;
    }

搜尋陣列中此元素 並返回此元素所在的位置

  //找到某一個元素並得到他的位置index
    public int find(int e){
        for(int i=0;i<size;i++){
            if(data[i]==e)
                return i;
        }
        return -1;
    }

刪除指定位置的元素

陣列向左移後,size也相對向左移一位到100,100不影響之後的操作

 //從陣列刪除index位置的元素,並返回該元素
    public int remove(int index){
        if(index<0||index>size)
            throw  new IllegalArgumentException("Remove is Fail,Index Is Illegal");
        for(int i=index+1;i<size;i++)
            data[i-1]=data[i];
        size--;//向左移
        return data[index];
    }

刪除第一個元素和最後一個元素

   // 從陣列中刪除第一個元素, 返回刪除的元素
    public int removeFirst(){
        return remove(0);
    }

    // 從陣列中刪除最後一個元素, 返回刪除的元素
    public int removeLast(){
        return remove(size - 1);
    }

從陣列刪除某個元素

    // 從陣列中刪除元素e
    public void removeElement(int e){
        int index = find(e);
        if(index != -1)
            remove(index);
    }

在Main中對自定義陣列進行操作

public class Main {

    public static void main(String[] args) {

    	Array arr = new Array(20);

    	for(int i=0;i<10;i++){//給陣列新增資料
    		arr.addLast(i);
		}
		System.out.println(arr);

    	//在位置1裡新增資料100
    	arr.add(1,100);
		System.out.println(arr);

		//在陣列第一個位置裡新增資料100
		arr.addFirst(99);
		System.out.println(arr);

		//陣列是否有某一個元素
		System.out.println(arr.contain(2));
		//查詢某個元素,返回它的index
		System.out.println(arr.find(2));
		//刪除某一個元素,返回該元素
		System.out.println(arr.remove(2));


	}
}
Array: size=10, capacity=20
[0,1,2,3,4,5,6,7,8,9]
Array: size=11, capacity=20
[0,100,1,2,3,4,5,6,7,8,9]
Array: size=12, capacity=20
[99,0,100,1,2,3,4,5,6,7,8,9]
true
4
1

六、使用泛型

  • 讓我們的資料型別可以放置"任何"資料型別
  • 不可是8種基本資料型別,只能是類物件
  • 每個基本資料型別都有相應的包裝類
public class Array {
    private int[] data;
    private int size;

    //構建一個帶參構造,給data陣列開闢空間為Capacity
    public Array(int Capacity) {
        data = new int[Capacity];
        size = 0;

    }

修改相應程式碼 ,將int換成E,不指定它是哪種資料型別

//Array存放的資料型別是E
public class Array<E>{
private E[] data;
....
public Array(int capacity){
data=(E)new Object[capacity];
...
 // 在index索引的位置插入一個新元素e
    public void add(int index, E e){
...}
 // 從陣列中刪除index位置的元素, 返回刪除的元素
    public E remove(int index){
...
}
  Array<Integer> arr = new Array<>(20);

 

將之前的程式碼轉成泛型的例子

Array.java

public class Array<E> {

    private E[] data;
    private int size;

    // 建構函式,傳入陣列的容量capacity構造Array
    public Array(int capacity){
        data = (E[])new Object[capacity];
        size = 0;
    }

    // 無引數的建構函式,預設陣列的容量capacity=10
    public Array(){
        this(10);
    }

    // 獲取陣列的容量
    public int getCapacity(){
        return data.length;
    }

    // 獲取陣列中的元素個數
    public int getSize(){
        return size;
    }

    // 返回陣列是否為空
    public boolean isEmpty(){
        return size == 0;
    }

    // 在index索引的位置插入一個新元素e
    public void add(int index, E e){

        if(size == data.length)
            throw new IllegalArgumentException("Add failed. Array is full.");

        if(index < 0 || index > size)
            throw new IllegalArgumentException("Add failed. Require index >= 0 and index <= size.");

        for(int i = size - 1; i >= index ; i --)
            data[i + 1] = data[i];

        data[index] = e;

        size ++;
    }

    // 向所有元素後新增一個新元素
    public void addLast(E e){
        add(size, e);
    }

    // 在所有元素前新增一個新元素
    public void addFirst(E e){
        add(0, e);
    }

    // 獲取index索引位置的元素
    public E get(int index){
        if(index < 0 || index >= size)
            throw new IllegalArgumentException("Get failed. Index is illegal.");
        return data[index];
    }

    // 修改index索引位置的元素為e
    public void set(int index, E e){
        if(index < 0 || index >= size)
            throw new IllegalArgumentException("Set failed. Index is illegal.");
        data[index] = e;
    }

    // 查詢陣列中是否有元素e
    public boolean contains(E e){
        for(int i = 0 ; i < size ; i ++){
            if(data[i].equals(e))
                return true;
        }
        return false;
    }

    // 查詢陣列中元素e所在的索引,如果不存在元素e,則返回-1
    public int find(E e){
        for(int i = 0 ; i < size ; i ++){
            if(data[i].equals(e))
                return i;
        }
        return -1;
    }

    // 從陣列中刪除index位置的元素, 返回刪除的元素
    public E remove(int index){
        if(index < 0 || index >= size)
            throw new IllegalArgumentException("Remove failed. Index is illegal.");

        E ret = data[index];
        for(int i = index + 1 ; i < size ; i ++)
            data[i - 1] = data[i];
        size --;
        data[size] = null; // loitering objects != memory leak
        return ret;
    }

    // 從陣列中刪除第一個元素, 返回刪除的元素
    public E removeFirst(){
        return remove(0);
    }

    // 從陣列中刪除最後一個元素, 返回刪除的元素
    public E removeLast(){
        return remove(size - 1);
    }

    // 從陣列中刪除元素e
    public void removeElement(E e){
        int index = find(e);
        if(index != -1)
            remove(index);
    }

    @Override
    public String toString(){

        StringBuilder res = new StringBuilder();
        res.append(String.format("Array: size = %d , capacity = %d\n", size, data.length));
        res.append('[');
        for(int i = 0 ; i < size ; i ++){
            res.append(data[i]);
            if(i != size - 1)
                res.append(", ");
        }
        res.append(']');
        return res.toString();
    }
}

Student類來做陣列的資料物件

public class Student {

    private String name;
    private int score;

    public Student(String studentName, int studentScore){
        name = studentName;
        score = studentScore;
    }

    @Override
    public String toString(){
        return String.format("Student(name: %s, score: %d)", name, score);
    }

    public static void main(String[] args) {

        Array<Student> arr = new Array<>();
        arr.addLast(new Student("Alice", 100));
        arr.addLast(new Student("Bob", 66));
        arr.addLast(new Student("Charlie", 88));
        System.out.println(arr);
    }
}

結果:

Array: size=3, capacity=10
[Student(name:Alice, score:100),Student(name:Bob score:66),Student(name:Charlie, score:88)]

七、動態陣列

原來的陣列達到最大的長度,要再末尾新增元素

新開闢一個newData是原來陣列length的兩倍

將原來的陣列轉移到新陣列(迴圈遍歷一遍)

data指向新的陣列

    // 在index索引的位置插入一個新元素e
    public void add(int index, E e){

        if(index < 0 || index > size)
            throw new IllegalArgumentException("Add failed. Require index >= 0 and index <= size.");

        //如果size達到陣列的長度
        if(size == data.length)
            resize(2 * data.length);

        for(int i = size - 1; i >= index ; i --)
            data[i + 1] = data[i];

        data[index] = e;

        size ++;
    }

remove也有進行縮容

 // 從陣列中刪除index位置的元素, 返回刪除的元素
    public E remove(int index){
        if(index < 0 || index >= size)
            throw new IllegalArgumentException("Remove failed. Index is illegal.");

        E ret = data[index];
        for(int i = index + 1 ; i < size ; i ++)
            data[i - 1] = data[i];
        size --;
        data[size] = null; // loitering objects != memory leak

        //當陣列個數是陣列長度的一半時進行縮容
        if(size == data.length / 2)
            resize(data.length / 2);
        return ret;
    }

  resize方法動態開闢新陣列

  // 將陣列空間的容量變成newCapacity大小
    private void resize(int newCapacity){

        E[] newData = (E[])new Object[newCapacity];
        for(int i = 0 ; i < size ; i ++)
            newData[i] = data[i];
        data = newData;
    }

八、簡單的複雜度分析

  • O(1),O(n),O(lgN),O(nLogn),O(n)
  • 大O描述的是演算法的執行時間和輸入資料之間的關係

 

九、均攤複雜度和防止複雜度振盪

resize的複雜度分析

 不可能每次新增元素都會觸發resize();

9次新增操作+8次轉移操作=17次操作

在均攤計算 ,時間複雜度是O(1);

addLast的均攤複雜度是O(1);

同理,我們看removeLast操作,均攤複雜度也是O(1);

複雜度振盪

當我們同時看到addLast和removeLast操作,每次都呼叫resize();

就是在元素滿在新增一個,就要擴容,然後再減少一個就要減容(resize)

以此看來原本O(1)的複雜度,卻猛的變成O(n)

出現問題的原因:removeLast時resize過於著急(Eager)

解決方案:Lazy

原本size==capacity/2時就要縮容,現在改成

新的策略:原本size==capacity/4才進行縮容一半,確定他之後不會增太多數量

    // 從陣列中刪除index位置的元素, 返回刪除的元素
    public E remove(int index){
        if(index < 0 || index >= size)
            throw new IllegalArgumentException("Remove failed. Index is illegal.");

        E ret = data[index];
        for(int i = index + 1 ; i < size ; i ++)
            data[i - 1] = data[i];
        size --;
        data[size] = null; // loitering objects != memory leak
        //實現lazy處理,到1/4才縮容,並且陣列的長度為1時不能再減半
        if(size == data.length / 4 && data.length / 2 != 0)
            resize(data.length / 2);
        return ret;
    }

 

(轉自發條魚)