數據結構之數組底層代碼

 1.整型數組

1)數組的插入、刪除、按照下標隨機訪問操作
2)數組中的數據時Int類型的

package array;
/**
 * 1)數組的插入、刪除、按照下標隨機訪問操作
 * 2)數組中的數據時Int類型的
 *
 */
public class Array {
	//定義保存整型數據data的數組
	private int[] data;
	//定義數組的長度
	private int n;
	//定義數組中元素的個數
	private int count;
	
	//構造方法,定義數組大小
	public Array(int capacity){
		this.data=new int[capacity];
		this.n=capacity;
		this.count=0;//一開始一個數據都沒有
	}
	
	//根據索引,找到數據中的元素並返回
	public int find(int index){
		if(index<0 || index>=count)
			return -1;
		return data[index];
	}
	
	//插入元素:頭部插入,尾部插入
	public boolean insert(int index,int value){
		//位置不合法
		if(index<0 || index>count){
			System.out.println("插入位置不合法");
			return false;
		}
		//數組爲空
//		if(index==count && count==0){
//			data[index]=value;
//			++count;
//			return true;
//		}
		//數組空間已滿
		if(count==n){
			System.out.println("空間已滿");
			return false;
		}
		//數組空間未滿,位置合法
		//將插入位置之後的數據向後搬移一位
		for(int i=count;i>index;--i){
			data[i]=data[i-1];
		}
		data[index]=value;
		++count;
		return true;
	}
	
	//根據索引,刪除數組中元素
	public boolean delete(int index){
		if(index<0 || index>=count) return false;
		//位置合法
		//將刪除位置之後的元素向前移動一位
		for(int i=index+1;i<count;++i){
			data[i-1]=data[i];
		}
		--count;
		return true;
	}
	
	public void printAll(){
		for(int i=0;i<count;++i){
			System.out.print(data[i]+" ");
		}
		System.out.println();
	}
	
	public static void main(String[] args) {
		Array array=new Array(5);
		array.printAll();
		array.insert(0, 3);
		array.insert(0, 4);
		array.insert(1, 5);
		array.insert(3, 8);
		array.insert(3, 10);
		array.delete(3);
		array.insert(3, 11);
		array.printAll();
	}
}

2.不確定類型數組GenericArray

package array;

public class GenericArray<T> {
	private T[] data;
    private int size;

    // 根據傳入容量,構造Array
    @SuppressWarnings("unchecked")
	public GenericArray(int capacity) {
        data = (T[]) new Object[capacity];
        size = 0;
    }

    // 無參構造方法,默認數組容量爲10
    public GenericArray() {
        this(10);
    }

    // 獲取數組容量
    public int getCapacity() {
        return data.length;
    }

    // 獲取當前元素個數
    public int count() {
        return size;
    }

    // 判斷數組是否爲空
    public boolean isEmpty() {
        return size == 0;
    }

    // 修改 index 位置的元素
    public void set(int index, T e) {
        checkIndex(index);
        data[index] = e;
    }

    // 獲取對應 index 位置的元素
    public T get(int index) {
        checkIndex(index);
        return data[index];
    }

    // 查看數組是否包含元素e
    public boolean contains(T e) {
        for (int i = 0; i < size; i++) {
            if (data[i].equals(e)) {
                return true;
            }
        }
        return false;
    }

    // 獲取對應元素的下標, 未找到,返回 -1
    public int find(T e) {
        for ( int i = 0; i < size; i++) {
            if (data[i].equals(e)) {
                return i;
            }
        }
        return -1;
    }


    // 在 index 位置,插入元素e, 時間複雜度 O(m+n)
    public void add(int index, T e) {
        checkIndex(index);
        // 如果當前元素個數等於數組容量,則將數組擴容爲原來的2倍
        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++;
    }

    // 向數組頭插入元素
    public void addFirst(T e) {
        add(0, e);
    }

    // 向數組尾插入元素
    public void addLast(T e) {
        add(size, e);
    }

    // 刪除 index 位置的元素,並返回
    public T remove(int index) {
        checkIndexForRemove(index);

        T ret = data[index];
        for (int i = index + 1; i < size; i++) {
            data[i - 1] = data[i];
        }
        size --;
        data[size] = null;

        // 縮容
        if (size == data.length / 4 && data.length / 2 != 0) {
            resize(data.length / 2);
        }

        return ret;
    }

    // 刪除第一個元素
    public T removeFirst() {
        return remove(0);
    }

    // 刪除末尾元素
    public T removeLast() {
        return remove(size - 1);
    }

    // 從數組中刪除指定元素
    public void removeElement(T e) {
        int index = find(e);
        if (index != -1) {
            remove(index);
        }
    }

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


    // 擴容方法,時間複雜度 O(n)
    private void resize(int capacity) {
        T[] newData = (T[]) new Object[capacity];

        for (int i = 0; i < size; i++) {
            newData[i] = data[i];
        }
        data = newData;
    }

    private void checkIndex(int index) {
        if (index < 0 || index > size) {
            throw new IllegalArgumentException("Add failed! Require index >=0 and index <= size.");
        }
    }

    private void checkIndexForRemove(int index) {
        if(index < 0 || index >= size) {
            throw new IllegalArgumentException("remove failed! Require index >=0 and index < size.");
        }
    }
}

3.基於數組實現LRU緩存

package linkedlist;

import java.util.HashMap;
import java.util.Map;
/**
 * Created by SpecialYang in 2018/12/7 2:00 PM.
 *
 * 基於數組實現的LRU緩存
 * 1. 空間複雜度爲O(n)
 * 2. 時間複雜度爲O(n)
 * 3. 不支持null的緩存
 */
public class LRUBasedArray<T> {
	private static final int DEFAULT_CAPACITY = (1 << 3);

    private int capacity;

    private int count;

    private T[] value;

    private Map<T, Integer> holder;

    public LRUBasedArray() {
        this(DEFAULT_CAPACITY);
    }

    public LRUBasedArray(int capacity) {
        this.capacity = capacity;
        value = (T[]) new Object[capacity];
        count = 0;
        holder = new HashMap<T, Integer>(capacity);
    }

    /**
     * 模擬訪問某個值
     * @param object
     */
    public void offer(T object) {
        if (object == null) {
            throw new IllegalArgumentException("該緩存容器不支持null!");
        }
        Integer index = holder.get(object);
        if (index == null) {
            if (isFull()) {
                removeAndCache(object);
            } else {
                cache(object, count);
            }
        } else {
            update(index);
        }
    }

    /**
     * 若緩存中有指定的值,則更新位置
     * @param end
     */
    public void update(int end) {
        T target = value[end];
        rightShift(end);
        value[0] = target;
        holder.put(target, 0);
    }

    /**
     * 緩存數據到頭部,但要先右移
     * @param object
     * @param end 數組右移的邊界
     */
    public void cache(T object, int end) {
        rightShift(end);
        value[0] = object;
        holder.put(object, 0);
        count++;
    }

    /**
     * 緩存滿的情況,踢出後,再緩存到數組頭部
     * @param object
     */
    public void removeAndCache(T object) {
        T key = value[--count];
        holder.remove(key);
        cache(object, count);
    }

    /**
     * end左邊的數據統一右移一位
     * @param end
     */
    private void rightShift(int end) {
        for (int i = end - 1; i >= 0; i--) {
            value[i + 1] = value[i];
            holder.put(value[i], i + 1);
        }
    }

    public boolean isContain(T object) {
        return holder.containsKey(object);
    }

    public boolean isEmpty() {
        return count == 0;
    }

    public boolean isFull() {
        return count == capacity;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < count; i++) {
            sb.append(value[i]);
            sb.append(" ");
        }
        return sb.toString();
    }

    static class TestLRUBasedArray {

        public static void main(String[] args) {
            testDefaultConstructor();
            testSpecifiedConstructor(4);
//            testWithException();
        }

        private static void testWithException() {
            LRUBasedArray<Integer> lru = new LRUBasedArray<Integer>();
            lru.offer(null);
        }

        public static void testDefaultConstructor() {
            System.out.println("======無參測試========");
            LRUBasedArray<Integer> lru = new LRUBasedArray<Integer>();
            lru.offer(1);
            lru.offer(2);
            lru.offer(3);
            lru.offer(4);
            lru.offer(5);
            System.out.println(lru);
            lru.offer(6);
            lru.offer(7);
            lru.offer(8);
            lru.offer(9);
            System.out.println(lru);
        }

        public static void testSpecifiedConstructor(int capacity) {
            System.out.println("======有參測試========");
            LRUBasedArray<Integer> lru = new LRUBasedArray<Integer>(capacity);
            lru.offer(1);
            System.out.println(lru);
            lru.offer(2);
            System.out.println(lru);
            lru.offer(3);
            System.out.println(lru);
            lru.offer(4);
            System.out.println(lru);
            lru.offer(2);
            System.out.println(lru);
            lru.offer(4);
            System.out.println(lru);
            lru.offer(7);
            System.out.println(lru);
            lru.offer(1);
            System.out.println(lru);
            lru.offer(2);
            System.out.println(lru);
        }
    }
}

 

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