lc周赛被LinkedList坑了以后来分析一下LinkedList和ArrayList的区分

1.结论

面向较多数据的增删则使用LinkedList,大量的访问则使用ArrayList,否则可能tle。如果LinkedList的话可能会让复杂度过高。

2.LinkedList的crud

首先,顾名思义,LinkedList是通过node类来存储数据的:

    private static class Node<E> {
        E item;
        Node<E> next;
        Node<E> prev;

        Node(Node<E> prev, E element, Node<E> next) {
            this.item = element;
            this.next = next;
            this.prev = prev;
        }
    }

是一个双向的链表;
我们再看一下增加节点的代码,可以看出来,默认接在链表的最后。

    void linkLast(E e) {
        final Node<E> l = last;//最后一个节点
        final Node<E> newNode = new Node<>(l, e, null);
        last = newNode;
        if (l == null)//如果最后一个空
            first = newNode;//将first指向新节点
        else
            l.next = newNode;//将新节点接在最后
        size++;
        modCount++;
    }

再看一下remove方法。

    public boolean remove(Object o) {
        if (o == null) {//为空的情况
            for (Node<E> x = first; x != null; x = x.next) {
                if (x.item == null) {
                    unlink(x);
                    return true;
                }
            }
        } else {
            for (Node<E> x = first; x != null; x = x.next) {//遍历链表,删除相等的对象
                if (o.equals(x.item)) {
                    unlink(x);//简单说就是把该节点的前后相连接,并进行一些特判
                    return true;
                }
            }
        }
        return false;
    }

可以看出来,remove方法的复杂度是o(n),最坏的情况是需要遍历一遍链表的。
再来看一下get方法。

    public E get(int index) {
        checkElementIndex(index);
        return node(index).item;
    }

其中关键方法是

    Node<E> node(int index) {
        // assert isElementIndex(index);

        if (index < (size >> 1)) {//判断index在前半段还是后半段
            Node<E> x = first;//从first开始遍历
            for (int i = 0; i < index; i++)
                x = x.next;
            return x;
        } else {
            Node<E> x = last;//从last开始遍历
            for (int i = size - 1; i > index; i--)
                x = x.prev;
            return x;
        }
    }

可以看出最坏的情况是访问了 n / 2 n/2 n/2个节点,复杂度是o(n),所以这里LinkedList方法的get方法是个隐性的o(n),如果在没注意的情况下可能会增大复杂度。

3. ArrayList的crud

ArrayList顾名思义是利用数组来存储数据的。

    /**
     * The array buffer into which the elements of the ArrayList are stored.
     * The capacity of the ArrayList is the length of this array buffer. Any
     * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
     * will be expanded to DEFAULT_CAPACITY when the first element is added.
     */
    transient Object[] elementData; // non-private to simplify nested class access
	    /**
     * Default initial capacity.
     */
    private static final int DEFAULT_CAPACITY = 10;

增加操作:

    public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // 确保数组规模足够存下新增加数据,否则执行grow方法
        elementData[size++] = e;
        return true;
    }
       private void ensureExplicitCapacity(int minCapacity) {
        modCount++;

        // 溢出处理
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }

所以grow方法是add方法复杂度方法的关键,因为这里涉及了数组的重新复制

    private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        // minCapacity is usually close to size, so this is a win:
        elementData = Arrays.copyOf(elementData, newCapacity);
    }

由于ArrayList借助了数组来实现,所以访问元素是很快的,o(1)即可

	    E elementData(int index) {
        return (E) elementData[index];
    }

get方法直接调用了elmentData就可以了,关键是remove方法复杂度
先看看remove方法的代码:

    public E remove(int index) {
        rangeCheck(index);//有效性检查
        modCount++;
        E oldValue = elementData(index);//获取待删除的元素
        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);//移动被删除后面的元素
        elementData[--size] = null; // clear to let GC do its work

        return oldValue;
    }

明显remove方法需要移动大量的元素来填补删除元素带来的空缺,最坏可能要移动n-1个节点,即删除第一个元素,所以复杂度是o(n)

4.总结

所以在需要list的场景下,我们需要根据不同的情况来选择ArrayList和LinkedList来满足复杂度的要求,否则tle。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值