Java 实现从数组删除指定位置元素

来源:互联网 发布:nginx和zookeeper 编辑:程序博客网 时间:2024/05/22 11:02

思路

1.  因为数组长度在初始化的时候是指定的并且不可变的,所以不能在原有的数组上直接进行删除操作,需要新建一个长度为当前长度减1的数组

2.  向新数组写数据


/**     * remove element at the specified position from the given array by loop     *      * @param array     * @param position     * @return     */    public static String[] removeElementByLoop(String[] array, int position) {        if (position < 0 || position > array.length) {            throw new IndexOutOfBoundsException("the position is out of the array indices");        }        long startTime = System.currentTimeMillis();        String[] newArray = new String[array.length - 1];        int index = position - 1;        for (int i = 0; i < array.length; i++) {            if (i < index) {                newArray[i] = array[i];            } else if (i > index) {                newArray[i - 1] = array[i];            }        }        System.out.println("took:" + (System.currentTimeMillis() - startTime) + " ms by loop solution");        return newArray;    }    /**     * remove element at the specified position from the given array by copy     *      * @param array     * @param position     * @return     */    public static String[] removeElementByCopy(String[] array, int position) {        int length = array.length;        if (position < 0 || position > length) {            throw new IndexOutOfBoundsException("the position is out of the array indices");        }        long startTime = System.currentTimeMillis();        String[] newArray = new String[array.length - 1];        int index = position - 1;        System.arraycopy(array, 0, newArray, 0, index);        if (index < length - 1) {            System.arraycopy(array, index + 1, newArray, index, length - index - 1);        }        System.out.println("took:" + (System.currentTimeMillis() - startTime) + " ms by copy solution");        return newArray;    }

对比:
从时间复杂度来说removeElementByCopy的性能能优于removeElementByLoop,因为removeElementByLoop是0(n)而removeElementByCopy是0(1)。

从空间复杂度来说removeElementByLoop的性能能优于removeElementByCopy,因为removeElementByCopy需要更多次的swap。


下面是测试结果
1. 当原数组长度较少的时候.

List<String> elements = new ArrayList<String>();for (int i = 0; i < 90000; i++) {    elements.add(i + "");}String[] array = elements.toArray(new String[elements.size()]);int position = 80000;removeElementByCopy(array, position);removeElementByLoop(array, position);
---->
took:0 ms by copy solution
took:2 ms by loop solution

2.
List<String> elements = new ArrayList<String>();for (int i = 0; i < 1000000; i++) {    elements.add(i + "");}String[] array = elements.toArray(new String[elements.size()]);int position = 80000;removeElementByCopy(array, position);removeElementByLoop(array, position);
---->
took:7 ms by copy solution
took:88 ms by loop solution


从测试结果可以看出来,在执行时间上的花费,removeElementByCopy的效率明显高于removeElementByLoop


0 0