1. Java中的数组
Java中的数组是静态数组,使用场景主要是“索引有语意”的情况,比如按学号查找分数,索引为学号。Java中数组的特点主要包括:
- 索引从0开始
- 声明时需要指定数组长度
- 最大的优点是查询速度快,通过索引直接定位
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循环 for(int score: scores) { System.out.println(score); } System.out.println("-----------"); //改 scores[0] = 96; for(int score: scores) { System.out.println(score); } } }
2. 封装自己的数组类
对于索引没有语意,以及索引有语意但使用Java中的静态数组将造成容量浪费的情况,可以基于Java的数组,二次封装属于自己的数组。
2.1 创建数组类
- 成员变量data静态数组用来存储数据
- 成员变量size用来表示数组实时存储的数据个数
public class Array { private int[] data; private int size; // 构造函数,传入数组的容量 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; } }
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]; } // 查找数组中元素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(); }
- 包含
// 查找数组中是否包含元素e public boolean contains(int e) { for(int i = 0;i<size;i++) { if (data[i] == e) return true; } return false; }
- 删除
// 从数组中删除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; } // 从数组中删除第一个元素,返回删除的元素 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); }
- 测试
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. 构建泛型和动态数组
3.1 使用泛型,数组可以存储各种类型的数据
- 泛型无法用来构建静态数组,需先用Object类创建,然后强转
- 泛型实现查找时,需要使用equals方法判断是否存在查找的元素
public class GenericArray<E> { private E[] data; private int size; // 构造函数,传入数组的容量 public GenericArray(int capacity) { data = (E[])new Object[capacity]; size = 0; } // 空构造,默认数组容量capacity=10 public GenericArray() { this(10); } // 获取数组的容量 public int getCapacity(){ return data.length; } // 获取数组中元素个数 public int getSize(){ return size; } // 返回数组是否为空 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; } // 查找数组中是否包含元素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; 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(); } }
- 测试上述构建的泛型数组类
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 动态数组
之前构建属于自己的数组,实际上还是基于静态数组来实现的,需要事先给定数组容量,当存储的数据超出数组容量时抛异常。本节使用扩容的方法来实现动态存储数组的功能,即当存储的数据超出数组容量时对数组进行扩容。
- 只需对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."); } // 如果存储数据长度已超过数组容量,则扩容 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方法,当存储的数据个数少于数组容量的一半时,缩减容量以节省空间
// 从数组中删除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; // 如果存储数据的个数已小于容量的一半,则缩减容量 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. 复杂度分析
4.1 简单复杂度分析
复杂度的表示方法有:
- O(1), O(n), O(lgn), O(nlogn), O(n^2), ...
- 大O描述的是算法的运行时间和输入数据之间的关系
以下面一段程序为例
public static int sum(int[] nums){ int sum = 0; for(int num: nums) sum + = num; return sum; }
其时间复杂度是O(n),其中n是nums中元素的个数,这是因为上述算法的执行时间与元素个数n呈线性关系。
这里其实忽略了定义sum、从数组中取处数据、返回sum等操作占用的时间,实际时间应该表示为T = c1*n+c2,但从复杂度分析的角度来处理,会忽略掉常数项和乘子项。比如以下两种算法的时间复杂度均为O(n):
- T = 2*n+2
- T = 2000*n+10000
而
- T = 1*n*n + 0
- T = 2*n*n + 300n + 10
的时间复杂度均为O(n^2)
4.2 分析动态数组的时间复杂度
- 添加操作
addLast(e) // 只需将元素添加到数组最后一位即可:O(1) addFirst(e) // 首先要将数组中的所有数据向后移一位,再添加: O(n) add(index,e) // 与插入数据的位置有关,结合概率论相关知识:O(n/2)=O(n)
通常考虑最坏的情况,添加操作的时间复杂度为O(n),即使加上resize操作(O(n)),时间复杂度也与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) // 需遍历数组中的所有元素:O(n) find(e) // O(n)
4.3 均摊复杂度分析和防止复杂度振荡
均摊复杂度分析
resize的时间复杂度为O(n),但add操作并不会每次都会触发resize:
假设capacity = n,n+1次add操作,才会触发一次resize,总共将进行2n+1次操作,均摊下来,每次add操作,进行2次基本操作,均摊的时间复杂度是O(1)!remove操作的均摊复杂度也为O(1)。复杂度振荡
当数组容量已满时,重复循环执行addLast 和 removeLast 操作,会不断触发resize,时间复杂度为O(n)。这样在实际问题中并不合适,主要是resize太过勤快,解决方案也很简单,将remove操作中的resize修改得“懒一些”即可:// 从数组中删除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; // 如果存储数据的个数已小于容量的一半,则缩减容量 // 惰性,如果存储数据的个数已小于容量的1/4,则缩减一半容量 if(size==data.length/4) { resize(data.length/2); } return ret; }
5. 总结
这节课主要学习了Java中的静态数组,静态数组适用于索引有语意的情况,在很多情况下,静态数组并不适用,于是我们基于静态数组构造了属于自己的数组类,实现了增、删、改、查等功能,然后进一步借助泛型,使得数组类支持存储各种类型的数据,但其本质依然需要给定数组容量,不够灵活,因此在此基础上,我们又构造了动态数组,增加了数组实时扩容的功能。最后介绍了时间复杂度的一些概念以及分析算法时间复杂度的流程,对算法与数据结构中所要学习的内容有了一个大概的认知。