简体   繁体   English

删除数组元素后如何移位?

[英]How to shift array elements after removing one?

I need to add a shift function only with loops (it means I can't use any ListArray method et simila, so this is not a copy of any other question with those methods.) to this method which removes a specific integer from a given array, and put the outcome into another array, and then returning it. 我只需要在循环中添加平移函数(这意味着我不能使用任何ListArray方法或类似方法,因此这不是这些方法的任何其他问题的副本。)到此方法中,该方法从给定的值中删除特定的整数数组,然后将结果放入另一个数组,然后将其返回。

public static int[] removeInt(int v, int[] in) {

    int length = 0;
    length = in.length;
    int[] toReturn = new int[length];

    for (int b = 0; b < length; b++) {
        toReturn[b] = 0;
    }

    for (int i = 0; i < length; i++) {
        if (in[i] != v) {
            toReturn[i] = in[i];
        }
    }

    return toReturn;
}

If the input for the array is {1, 2, 3, 4, 5}, and the number to remove is {2}, the output will be {1 0 3 4 5}, but it needs to be {1 3 4 5}, and I can't find a way to shift numbers to the left. 如果数组的输入为{1、2、3、4、5},要删除的数字为{2},则输出将为{1 0 3 4 5},但必须为{1 3 4 5},我找不到将数字向左移动的方法。

'v' comes from the main, user input. “ v”来自主要的用户输入。 Same for 'in', fullfilled before by the user. 与“ in”相同,由用户之前填写。

Have you considered using a LinkedList ? 您是否考虑过使用LinkedList This internally manages the array so you don't need to deal with moving the elements yourself; 这在内部管理数组,因此您无需自己移动元素。 you can just call remove() . 您可以只调用remove()

You will have to iterate over the array two times: The first time, you count how often v is contained in in . 您将必须遍历两次数组:第一次,您计算v在in包含的频率。 If count is 0, you can return in, otherwise you would have to create a new array of length in.length - count . 如果count为0,则可以返回,否则必须创建一个长度为in.length - count的新数组。 Then again you have to iterate over in and add every value that is not v to your Array. 话又说回来,你必须遍历in ,并添加每个值不是V到您的阵列。

int count = 0;

    for(int i: in) {
        if (i==v) {
            count++;
        }
    }

    int[] result = new int[in.length-count];
    int pos=0;
    for(int i: in) {
        if (i!=v) {
            result[pos] = i;
            pos++;
        }
    }

But you could use Collections to make it easier: 但是您可以使用Collections使其更容易:

public static void main(String[] args) {
    int v = 2;
    int[] in = new int[]{1, 2, 3, 4, 5};

    List<Integer> list = new ArrayList<>();
    for(int i: in) {
        if (i!=v) {
            list.add(i);
        }
    }

    Integer[] result = list.toArray(new Integer[]{});
}

The disadvantage of this, however, would be that you have an Array of Integer and not of int. 但是,这样做的缺点是您拥有一个整数数组而不是一个整数数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM