玩轉(zhuǎn)數(shù)據(jù)結(jié)構(gòu)1-數(shù)組

1. Java中的數(shù)組

Java中的數(shù)組是靜態(tài)數(shù)組,使用場景主要是“索引有語意”的情況,比如按學號查找分數(shù),索引為學號。Java中數(shù)組的特點主要包括:

  • 索引從0開始
  • 聲明時需要指定數(shù)組長度
  • 最大的優(yōu)點是查詢速度快,通過索引直接定位
public class Main {

    public static void main(String[] args) {
        int[] arr = new int[10];
        
        //軟編碼: length
        for(int i = 0;i<arr.length;i++) {
            arr[i] = i;
        }
        
        int[] scores = new int[] {10,99,96};
        for(int i = 0;i<scores.length;i++) {
            System.out.println(scores[i]);
        }
        System.out.println("-----------");
        
        //增強for循環(huán)
        for(int score: scores) {
            System.out.println(score);
        }
        System.out.println("-----------");
        
        //改
        scores[0] = 96;
        for(int score: scores) {
            System.out.println(score);
        }
    }
}

2. 封裝自己的數(shù)組類

對于索引沒有語意,以及索引有語意但使用Java中的靜態(tài)數(shù)組將造成容量浪費的情況,可以基于Java的數(shù)組,二次封裝屬于自己的數(shù)組。

2.1 創(chuàng)建數(shù)組類
  • 成員變量data靜態(tài)數(shù)組用來存儲數(shù)據(jù)
  • 成員變量size用來表示數(shù)組實時存儲的數(shù)據(jù)個數(shù)
public class Array {
    private int[] data;
    private int size;
    
    // 構(gòu)造函數(shù),傳入數(shù)組的容量
    public Array(int capacity) {
        data = new int[capacity];
        size = 0;
    }
    
    // 空構(gòu)造,默認數(shù)組容量capacity=10
    public Array() {
        this(10);
    }
    
    // 獲取數(shù)組的容量
    public int getCapacity(){
        return data.length;
    }
    
    // 獲取數(shù)組中元素個數(shù)
    public int getSize(){
        return size;
    }
    
    // 返回數(shù)組是否為空
    public boolean isEmpty() {
        return size == 0;
    }
}
2.2 增、刪、改、查
  • 增加元素
// 向所有元素后添加一個新元素
public void addLast(int e) {
    if(size == data.length) {
        throw new IllegalArgumentException("AddLast failed. Array is full.");
    }
        
    data[size] = e;
    size++;
    //add(size,e);
}

 // 向所有元素前添加一個新元素
public void addFirst(int e) {
    add(0,e);
}
    
// 向指定位置插入一個新元素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 ++;
}
  • 查詢與查找
// 獲取index索引位置的元素
public int get(int index) {
    if(index <0 || index >=size) {
        throw new IllegalArgumentException("Get failed. Index is illegal.");
    }
    return data[index];
}
// 查找數(shù)組中元素e所在的索引,如果不存在元素e,則返回-1
public int find(int e) {
    for(int i = 0;i<size;i++) {
        if (data[i] == e)
            return i;
    }
    return -1;      
}
  • 修改
// 修改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;
}
  • 測試
@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();
}
  • 包含
// 查找數(shù)組中是否包含元素e
public boolean contains(int e) {
    for(int i = 0;i<size;i++) {
        if (data[i] == e)
            return true;
    }
    return false;
}
  • 刪除
// 從數(shù)組中刪除index索引位置的元素,返回刪除的元素
public int remove(int index) {
    if(index<0 || index > size) {
        throw new IllegalArgumentException("Remove failed. Index is illegal.");
    }
    int ret = data[index];
    for(int i = index + 1;i<size;i++) {
        data [i - 1] = data[i]; 
    }
    size--;
    return ret;
}
    
// 從數(shù)組中刪除第一個元素,返回刪除的元素
public int removeFirst() {
    return remove(0);
}
    
// 從數(shù)組中刪除最后元素,返回刪除的元素
public int removeLast() {
    return remove(size-1);
}
    
// 從數(shù)組刪除元素e
public void removeElement(int e) {
    int index = find(e);
    if(index != -1)
        remove(index);
}
  • 測試
Array array = new Array(20);
for(int i = 0;i<10;i++) {
    array.addLast(i);
}
System.out.println(array);
// Array: size = 10, capacity = 20 
// [0,1,2,3,4,5,6,7,8,9]
        
array.add(1, 100);
System.out.println(array);
// Array: size = 11, capacity = 20 
// [0,100,1,2,3,4,5,6,7,8,9]
        
array.addFirst(-1);;
System.out.println(array);
// Array: size = 12, capacity = 20 
// [-1,0,100,1,2,3,4,5,6,7,8,9]
        
array.set(0, -2);
System.out.println(array);
// Array: size = 12, capacity = 20 
// [-2,0,100,1,2,3,4,5,6,7,8,9]
        
System.out.println(array.contains(10));
// false
        
System.out.println(array.find(2));
// 4
        
array.removeFirst();
System.out.println(array);
// Array: size = 11, capacity = 20 
// [0,100,1,2,3,4,5,6,7,8,9]
        
array.remove(1);
System.out.println(array);
// Array: size = 10, capacity = 20 
// [0,1,2,3,4,5,6,7,8,9]
        
array.removeElement(100);
System.out.println(array);
// Array: size = 10, capacity = 20 
// [0,1,2,3,4,5,6,7,8,9]

3. 構(gòu)建泛型和動態(tài)數(shù)組

3.1 使用泛型,數(shù)組可以存儲各種類型的數(shù)據(jù)
  • 泛型無法用來構(gòu)建靜態(tài)數(shù)組,需先用Object類創(chuàng)建,然后強轉(zhuǎn)
  • 泛型實現(xiàn)查找時,需要使用equals方法判斷是否存在查找的元素
public class GenericArray<E> {
    private E[] data;
    private int size;
    
    // 構(gòu)造函數(shù),傳入數(shù)組的容量
    public GenericArray(int capacity) {
        data = (E[])new Object[capacity];
        size = 0;
    }
    
    // 空構(gòu)造,默認數(shù)組容量capacity=10
    public GenericArray() {
        this(10);
    }
    
    // 獲取數(shù)組的容量
    public int getCapacity(){
        return data.length;
    }
    
    // 獲取數(shù)組中元素個數(shù)
    public int getSize(){
        return size;
    }
    
    // 返回數(shù)組是否為空
    public boolean isEmpty() {
        return size == 0;
    }
    
    // 向所有元素后添加一個新元素
    public void addLast(E e) {
        if(size == data.length) {
            throw new IllegalArgumentException("AddLast failed. Array is full.");
        }
        
        data[size] = e;
        size++;
        
        //add(size,e);
    }
    
    // 向所有元素前添加一個新元素
    public void addFirst(E e) {
        add(0,e);
    }
    
    // 向指定位置插入一個新元素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 ++;
    }
    
    // 獲取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;
    }
    
    // 查找數(shù)組中是否包含元素e
    public boolean contains(E e) {
        for(int i = 0;i<size;i++) {
            if (data[i].equals(e))
                return true;
        }
        return false;
    }
    
    // 查找數(shù)組中元素e所在的索引,如果不存在元素e,則返回-1
    public int find(E e) {
        for(int i = 0;i<size;i++) {
            if (data[i].equals(e))
                return i;
        }
        return -1;      
    }
    
    // 從數(shù)組中刪除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;
        return ret;
    }
    
    // 從數(shù)組中刪除第一個元素,返回刪除的元素
    public E removeFirst() {
        return remove(0);
    }
    
    // 從數(shù)組中刪除最后元素,返回刪除的元素
    public E removeLast() {
        return remove(size-1);
    }
    
    // 從數(shù)組刪除元素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();
    }
}
  • 測試上述構(gòu)建的泛型數(shù)組類
package com.xkzhai.genericArray;

public class Student {
    private String stuName;
    private int score;
    
    public Student(String stuName,int score) {
        this.stuName = stuName;
        this.score = score;
    }
    
    @Override
    public String toString() {
        return String.format("Student(Name: %s , Score: %d )", stuName,score);
    }
    
    public static void main(String[] args) {
        GenericArray<Student> students = new GenericArray<Student>();
        students.addLast(new Student("Alice", 100));
        students.addLast(new Student("Bob", 69));
        students.addLast(new Student("Tom", 80));
        System.out.println(students);
        // Array: size = 3, capacity = 10 
        // [Student(Name: Alice , Score: 100 ),Student(Name: Bob , Score: 69 ),Student(Name: Tom , Score: 80 )]
    }
}
3.2 動態(tài)數(shù)組

之前構(gòu)建屬于自己的數(shù)組,實際上還是基于靜態(tài)數(shù)組來實現(xiàn)的,需要事先給定數(shù)組容量,當存儲的數(shù)據(jù)超出數(shù)組容量時拋異常。本節(jié)使用擴容的方法來實現(xiàn)動態(tài)存儲數(shù)組的功能,即當存儲的數(shù)據(jù)超出數(shù)組容量時對數(shù)組進行擴容。

  • 只需對add方法進行改造即可,增加resize方法
// 向指定位置插入一個新元素e
public void add(int index,E e) {    
    if(index<0 || index > size) {
        throw new IllegalArgumentException("Add failed. Require index >= 0 and index <= size.");            
    }
        
    // 如果存儲數(shù)據(jù)長度已超過數(shù)組容量,則擴容
    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 ++;
}
      
private void resize(int newCapacity) {
    E newData[] = (E[])new Object[newCapacity];
    for(int i = 0;i<size;i++) {
        newData[i] = data[i];
    }
    data = newData;
}
  • 修改remove方法,當存儲的數(shù)據(jù)個數(shù)少于數(shù)組容量的一半時,縮減容量以節(jié)省空間
// 從數(shù)組中刪除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;
    // 如果存儲數(shù)據(jù)的個數(shù)已小于容量的一半,則縮減容量
    if(size==data.length/2) {
        resize(data.length/2);
    }
    return ret;
}
  • 對上述功能進行測試
DynamicArray array = new DynamicArray();
for(int i = 0;i<10;i++) {
    array.addLast(i);
}
System.out.println(array);
// Array: size = 10, capacity = 10 
// [0,1,2,3,4,5,6,7,8,9]
    
array.add(1, 100);
System.out.println(array);
// Array: size = 11, capacity = 20 
// [0,100,1,2,3,4,5,6,7,8,9]
    
array.addFirst(-1);;
System.out.println(array);
// Array: size = 12, capacity = 20 
// [-1,0,100,1,2,3,4,5,6,7,8,9]
    
array.removeFirst();
System.out.println(array);
// Array: size = 11, capacity = 20 
// [0,100,1,2,3,4,5,6,7,8,9]
    
array.remove(1);
System.out.println(array);
// Array: size = 10, capacity = 10 
// [0,1,2,3,4,5,6,7,8,9]
    
array.removeElement(7);
System.out.println(array);
// Array: size = 9, capacity = 10 
// [0,1,2,3,4,5,6,8,9]

4. 復(fù)雜度分析

4.1 簡單復(fù)雜度分析

復(fù)雜度的表示方法有:

  • O(1), O(n), O(lgn), O(nlogn), O(n^2), ...
  • 大O描述的是算法的運行時間和輸入數(shù)據(jù)之間的關(guān)系

以下面一段程序為例

public static int sum(int[] nums){
    int sum = 0;
    for(int num: nums) sum + = num;
    return sum;
}

其時間復(fù)雜度是O(n),其中n是nums中元素的個數(shù),這是因為上述算法的執(zhí)行時間與元素個數(shù)n呈線性關(guān)系。

這里其實忽略了定義sum、從數(shù)組中取處數(shù)據(jù)、返回sum等操作占用的時間,實際時間應(yīng)該表示為T = c1*n+c2,但從復(fù)雜度分析的角度來處理,會忽略掉常數(shù)項和乘子項。比如以下兩種算法的時間復(fù)雜度均為O(n):

  • T = 2*n+2
  • T = 2000*n+10000

  • T = 1*n*n + 0
  • T = 2*n*n + 300n + 10

的時間復(fù)雜度均為O(n^2)

4.2 分析動態(tài)數(shù)組的時間復(fù)雜度
  • 添加操作
addLast(e) // 只需將元素添加到數(shù)組最后一位即可:O(1)
addFirst(e) // 首先要將數(shù)組中的所有數(shù)據(jù)向后移一位,再添加: O(n)
add(index,e) // 與插入數(shù)據(jù)的位置有關(guān),結(jié)合概率論相關(guān)知識:O(n/2)=O(n)

通常考慮最壞的情況,添加操作的時間復(fù)雜度為O(n),即使加上resize操作(O(n)),時間復(fù)雜度也與n呈線性關(guān)系,仍為O(n)。

  • 刪除操作(同添加操作)
removeLast() // O(1)
removeFirst() // O(n)
remove(index) // O(n/2)=O(n)
  • 修改操作
set(index,e) // 按索引賦值即可:O(1)
  • 查找操作
get(index) // 直接按索引取值:O(1)
contains(e) // 需遍歷數(shù)組中的所有元素:O(n)
find(e) // O(n)
4.3 均攤復(fù)雜度分析和防止復(fù)雜度振蕩
  • 均攤復(fù)雜度分析
    resize的時間復(fù)雜度為O(n),但add操作并不會每次都會觸發(fā)resize:
    假設(shè)capacity = n,n+1次add操作,才會觸發(fā)一次resize,總共將進行2n+1次操作,均攤下來,每次add操作,進行2次基本操作,均攤的時間復(fù)雜度是O(1)!remove操作的均攤復(fù)雜度也為O(1)。

  • 復(fù)雜度振蕩
    當數(shù)組容量已滿時,重復(fù)循環(huán)執(zhí)行addLast 和 removeLast 操作,會不斷觸發(fā)resize,時間復(fù)雜度為O(n)。這樣在實際問題中并不合適,主要是resize太過勤快,解決方案也很簡單,將remove操作中的resize修改得“懶一些”即可:

      // 從數(shù)組中刪除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;
          // 如果存儲數(shù)據(jù)的個數(shù)已小于容量的一半,則縮減容量
          // 惰性,如果存儲數(shù)據(jù)的個數(shù)已小于容量的1/4,則縮減一半容量
          if(size==data.length/4) {
              resize(data.length/2);
          }
          return ret;
      }
    

5. 總結(jié)

這節(jié)課主要學習了Java中的靜態(tài)數(shù)組,靜態(tài)數(shù)組適用于索引有語意的情況,在很多情況下,靜態(tài)數(shù)組并不適用,于是我們基于靜態(tài)數(shù)組構(gòu)造了屬于自己的數(shù)組類,實現(xiàn)了增、刪、改、查等功能,然后進一步借助泛型,使得數(shù)組類支持存儲各種類型的數(shù)據(jù),但其本質(zhì)依然需要給定數(shù)組容量,不夠靈活,因此在此基礎(chǔ)上,我們又構(gòu)造了動態(tài)數(shù)組,增加了數(shù)組實時擴容的功能。最后介紹了時間復(fù)雜度的一些概念以及分析算法時間復(fù)雜度的流程,對算法與數(shù)據(jù)結(jié)構(gòu)中所要學習的內(nèi)容有了一個大概的認知。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容