简单的时间复杂度分析

O(1),O(n),O(lgn),O(nlgn),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呈线性关系.

为什么要用大O,叫做O(n)?

忽略常熟.实际时间T=c1*n+c2

O()渐进时间复杂度,描述n趋近于无穷大的情况.

分析动态数组的时间复杂度:

前三篇代码中addLast(e)的时间复杂度为O(1). 

表示无论有多少个元素,addLast都能在常数个的时间内完成.

addFirst(e)的时间复杂度为O(n),

add(index,e)的时间复杂度为O(n/2)=>O(n)

综合来说添加操作的时间复杂度为O(n);

resize的时间复杂度为O(n);

removeLast(e)的时间复杂度为O(1),

removeFirst(e)的时间复杂度为O(n),

remove(index,e)的时间复杂度为O(n/2)=>O(n)

综合来说添加操作的时间复杂度为O(n);

修改操作

set(index,e)  O(1)

查找操作

get(index) O(1)

contains(e)  O(n)

find(e)   O(n)

对于动态数组来说:

增:O(n)

删:O(n)

改:已知索引O(1),未知索引O(n)

查:已知索引O(1),未知索引O(n)

resize的时间复杂度分析:

假设当前capacity=n,n+1次addLast,出发了resize,总共进行了2n+1次基本操作

平均,每次addLast操作进行了两次基本操作

这样均摊计算,时间复杂度是O(1)的!

均摊复杂度amortized time complexity

resize O(n)

addLast的均摊复杂度为O(1)

同理,我们可以看removeLast操作,均摊复杂度也为O(1)

复杂度震荡:

 

 出现问题的原因:removeLast时resize过于着急(Eager)

 解决方案:Lazy模式

当size == capacity/4时,才将capacity减半

package com.practice.Array;

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 getSize(){
        return size;
    }

    //获取数组的容量
    public int getCapacity(){
        return data.length;
    }

    //返回数组是否为空
    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);
    }

    //在第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.");
        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 ++;
    }

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

    //修改index索引位置的元素
    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("Set 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 / 4 && data.length / 2 != 0)
            resize(data.length / 2);
        return ret;
    }

    //从数组中删除第一个元素,返回删除的元素
    public E removeFirst(){
        return remove(0);
    }

    //从数组中删除最后一个元素,返回删除的元素
    public E removeLast(){
        return remove(size - 1);
    }

    /**
     * 可能存在多个元素e,稍后自己写findAll和removeAllElement
     * @param e
     */

    //从数组中删除元素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();
    }

    //重置数组大小长度
    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地方缩容的修改

posted on 2022-07-06 21:26  网恋被骗两千八  阅读(40)  评论(0)    收藏  举报