首页 > 解决方案 > 如何删除固定数组中的元素

问题描述

我目前正在研究固定数组上的删除方法。下面是delete方法的实现。它在第一个 for 循环中所做的是,如果数据在数组上匹配,它会获取索引。对于下一个 if 和 for 循环,它应该移动索引的内容,例如,如果删除的元素位于长度为 5 的数组的第二或第三索引处。如果元素已成功删除,则返回 true在数组中,如果不是,则为 false。

public boolean delete(E data) {
    int index = -1;
    int size = list.length;

    for (int i = 0; i < list.length; i++) { // for getting what index in the array
        if (data == list[i]) {              // is the element in if there is a match
            index = i;
        }
    }

    if (index > -1) {                               // for swapping the index when
        final int newArraySize;                     // the element is deleted in the 
        if ((newArraySize = size - 1) > index) {    // between first-2nd to the last
            for (int x = 0; x < list.length; x++) { // index in the array.
                    if (list[x] == null) {
                        for (int y = 0; y < x; y++) {
                            // move items
                            list[y] = list[y+1];
                        }
                    }
            }
        }
        list[size = newArraySize] = null;
        return true;
    }

    return false;
}

当我尝试运行它时,它不会删除元素。我在执行交换索引部分时遇到问题。我需要帮助。

标签: javaarrays

解决方案


您的解决方案的时间复杂度为 O(nxn)。相反,您可以从被删除元素的索引开始,并从被删除元素的索引交换所有元素。

for (int i = index; i < list.length - 1; i++) {
    list[i] = list[i + 1];
}

但上述解决方案可能会保留相同大小的数组并具有重复元素。

我会建议使用两个数组解决方案,它会增加一点空间复杂性,但会有效地删除元素并减小数组大小。您还需要返回这个更新的数组。

int[] copy = new int[list.length - 1];

for (int i = 0, j = 0; i < list.length; i++) {
    if (i != index) {
        copy[j++] = list[i];
    }
}

推荐阅读