建议:不要小瞧数组。把下面数组的代码敲一遍。数组就差不多了。
1、数组相关知识
在做算法的过程中,数组也涉及的挺多的,当然这里说的数组当然是动态数组。对数据的操作增删查改需要熟练。Java中使用集合多一些,但是算法中数组题目挺多的。
数组是把数据码成一排进行存放。存储相同类型的数据类型。索引从0开始。
2、数组代码
数组最大的优点就是快速查询,通过索引快速定位。现在制作自己的数组类。
这里是泛型类Array<E>。这里面比较重要的是数组的扩容。和删除数组的时候数组的减容量。
package com.algorithm.array;
import org.omg.CORBA.Object;
import java.util.Arrays;
public class Array<E> {
// 定义数组,和数组动态的大小
private E[] data;
private int size;
// 初始化数组和动态数组容量
public Array(int capacity){
data = (E[]) new Object[capacity];
size = 0;
}
// 默认数组容量为10
public Array(){
this(10);
}
// 获取数字中元素的个数
public int getSize(){
return size;
}
// 获取数组中容量大小
public int getCapacity(){
return data.length;
}
// 判断数组是否为空,也就是没有元素,size==0,true,size!=0,返回的是false
public boolean isEmpty(){
return size == 0;
}
// 向数组中的最后一个元素后面添加一个元素
public void addLast(E element) {
/*if (size == getCapacity()){
throw new IllegalArgumentException("addLast is failed,array is full");
}
data[size] = element;
size++;*/
add(size,element);
}
// 在数组中的第一个元素之前添加一个元素
public void addFirst(E element){
add(0,element);
}
// 向 数组中index位置,插入一个新的元素e
public void add(int index,E element){
if (size == getCapacity()) {
throw new IllegalArgumentException("addLast is failed,array is full");
}
if (index < 0 || index > size) {
throw new IllegalArgumentException("addLast is failed,index < 0 || index > size,array is full");
}
// 遍历数组,index后的位置往后移动
for (int i = size - 1; i >=index ; i--) {
data[i + 1] = data[i];
}
data[index] = element;
size++;
}
// 获取index位置上的元素
public E get(int index){
if (index < 0 || index >= size) {
throw new IllegalArgumentException("index is illgal");
}
return data[index];
}
// 修改 index位置上的元素为e
public void set(int index, E element) {
if (index < 0 || index >= size) {
throw new IllegalArgumentException("index is illgal");
}
data[index] = element;
}
// 查找数组中是否含有元素e,是size,不是capacity,
// 0 1 2 3 size指向的是3,而位置0 1 2上有元素,i从0开始,i<size,i<3,那么就是 0 1 2
public boolean contains(E element){
for (int i = 0; i < size; i++) {
// 类对象值的比较
if (data[i].equals(element)) {
return true;
}
}
return false;
}
// 查找数组中的元素e所在的索引,如果不存在元素e,返回-1
public int find(E element){
for (int i = 0; i < size; i++) {
if (data[i].equals(element)) {
return i;
}
}
// 找不到的话返回-1
return -1;
}
// 删除index位置的元素,返回删除的元素
public E remove(int index){
if (index < 0 || index >= size) {
throw new IllegalArgumentException("RemoveFailed,Index is Failed");
}
E res = data[index];
// 后面的元素往前移动一个位置
for (int i = index + 1; index < size; i++) {
data[i - 1] = data[i];
}
size--;
return res;
}
// 删除数字中第一个元素,并返回元素
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() {
return "Array{" +
"data=" + Arrays.toString(data) +
", size=" + size +
'}';
}
}