【问题标题】:How to delete an item in the array and keeping the order the same?如何删除数组中的项目并保持顺序不变?
【发布时间】:2021-10-07 16:42:22
【问题描述】:

我正在处理这个项目,该项目允许我在数组中添加和删除元素。当我删除数组中的元素时,该空间中会出现一个零,并且代码应该在删除的值之后移动值以取代它。例如:在数组 {1, 2, 3, 4, 5} 中。我选择删除 3。我的输出应该是 {1, 2, 4, 5}。相反,我的输出是 {1, 2, 5, 4}。有人可以帮我弄清楚为什么会这样做吗?又该如何整改?

import java.util.Scanner;
import java.util.Arrays;

public class IntBag2 {
    private static final int INITIAL_SIZE = 20;
    private static int[] bag;
    private int capacity;

    public IntBag2() {
        bag = new int[INITIAL_SIZE];
    }

    public IntBag2(int capacity) {
        bag = new int[capacity];
    }

    public boolean add(int item) {
        if (capacity == bag.length)
            return false;

        bag[capacity++] = item;

        return true;
    }

    public boolean delete(int item) {
        for (int i = 0; i < capacity; i++) {
            if (bag[i] == item) {
                bag[i] = bag[--capacity];
                return true;
            }
        }

        return false;
    }

    @Override
    public String toString() {
        String result = "Bag: ";
        for (int i = 0; i < capacity; i++)
            result += bag[i] + " ";
        return result;
    }

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        IntBag2 intBag = new IntBag2();
        boolean done = false;

        while (!done) {
            System.out.println("1. Add an Item to the Array");
            System.out.println("2. Delete an item in the Array");
            System.out.println("3. toString");
            switch (input.nextInt()) {
            case 1:
                System.out.println("Add an Item to the Array");
                System.out.println(intBag.add(input.nextInt()));
                break;
            case 2:
                System.out.println("Delete Item of Array");
                System.out.println(intBag.delete(input.nextInt()));
                break;
            case 3:
                System.out.println("toString");
                System.out.println(intBag.toString());
                break;
            }
        }
        input.close();
    }

}

【问题讨论】:

  • 您可能想查看java.util.ArrayList 的来源——尤其是remove() 方法。
  • 我不允许使用数组列表,该项目是关于部分填充数组的。
  • 是的,但是您可以阅读源代码以了解事情是如何完成的。

标签: java arrays eclipse java.util.scanner


【解决方案1】:

delete 的更简单实现是允许“删除”数组中等于给定 item所有条目,并将剩余的条目有效地移到前面:

public boolean delete(int item) {
    System.out.println("deleting " + item); // for debug purposes
    int oldCapacity = capacity;
    for (int i = 0, j = 0; i < oldCapacity; i++) {
        if (bag[i] != item) {
            bag[j++] = bag[i];
        } else {
            capacity--;
        }
    }
    System.out.println("new capacity = " + capacity); // for debug

    // or use Arrays.fill(bag, capacity, oldCapacity, -1); instead of the loop
    for (int i = capacity; i < oldCapacity; i++) {
        bag[i] = -1; // mark free entries with -1 in the tail
    }

    return oldCapacity == capacity;
}

此外,如果在循环中使用多个连接,则方法 toString 应使用 StringBuilder,或者为简洁起见,可以使用来自 Arrays 的实用方法实现以下方法 print

public void print() {
    System.out.println(Arrays.toString(Arrays.copyOf(bag, capacity)));
}

测试:

IntBag ibag = new IntBag(10);
ibag.add(1);
ibag.add(3);
ibag.add(3);
ibag.add(2);
ibag.add(1);
ibag.print();
ibag.delete(2);
ibag.print();
ibag.delete(1);
ibag.print();

输出:

[1, 3, 3, 2, 1]
deleting 2
new capacity = 4
[1, 3, 3, 1]
deleting 1
new capacity = 2
[3, 3]

更新

只删除第一个条目而不创建新数组可以实现如下:

  • 跳过所有元素,直到检测到item 或到达bag 的结尾
  • 如果找到item,则将剩余元素移1,将-1写入最后一个元素,返回true
  • 否则返回false
public boolean deleteFirst(int item) {
    System.out.println("deleting first " + item);
    int id = 0;
    while (id < capacity && bag[id] != item) id++;
    if (id < capacity && bag[id] == item) {
        while (++id < capacity) {
            bag[id - 1] = bag[id];
        }
        bag[--capacity] = -1;
        return true;
    }
    return false;
}

测试:

IntBag ibag = new IntBag(10);
ibag.add(1); ibag.add(3); ibag.add(1); ibag.add(2); ibag.add(1);
ibag.print();
ibag.deleteFirst(1); ibag.print();
ibag.deleteFirst(1); ibag.print();
ibag.deleteFirst(1); ibag.print();

输出:

[1, 3, 1, 2, 1]
deleting first 1
[3, 1, 2, 1]
deleting first 1
[3, 2, 1]
deleting first 1
[3, 2]

【讨论】:

  • 我需要 delete 方法只删除第一次出现的项目而不是每次。我要求这种方法是因为我需要实现另一种方法来删除您提供给我的所有内容。现在我需要删除第一次出现的项目的方法。
  • @EzequielSoler,你可以查看更新
【解决方案2】:

使用bag[i] = bag[--capacity]; 行,您基本上可以获取数组中的最后一项并将其放置在已删除项的位置。

鉴于您使用的是int[](而不是Integer[]),我们不能将数组的索引指定为null。我们能做的最好的就是分配它-1 或创建一个新数组。

我决定从头开始创建一个新数组。以下方法可以解决问题。

public class IntBag2 {
    private static final int INITIAL_SIZE = 20;
    private static int[] bag;
    private int capacity;

    public IntBag2() {
        bag = new int[INITIAL_SIZE];
    }

    public IntBag2(int capacity) {
        bag = new int[capacity];
    }

    public boolean add(int item) {
        if (capacity == bag.length)
            return false;

        bag[capacity++] = item;

        return true;
    }

    public boolean delete(int item) {
        int[] newBag = new int[capacity];
        int newCapacity = capacity;
        boolean deleted = false;
        for (int i = 0, j = 0; i < capacity; i++) {
            if (bag[i] == item && !deleted) {
                deleted = true;
                newCapacity = capacity - 1;
            } else {
                newBag[j++] = bag[i];
            }
        }

        bag = newBag;
        capacity = newCapacity;
        return deleted;
    }

    @Override
    public String toString() {
        String result = "Bag: ";
        for (int i = 0; i < capacity; i++)
            result += bag[i] + " ";
        return result;
    }
}

【讨论】:

  • 那么如何更改它以获取数组中的下一项并将其放置在已删除项的位置?
  • 你可以使用来自 Apache Commons 的 ArrayUtils 吗?
  • 我为我的答案添加了一个可能的解决方案。如果它不适用于或用例,请告诉我。
  • 顺序是固定的,但现在的输出是 {1, 2, 4, 5, -1} 如果我要从数组 {1, 2, 3, 4, 5} 中删除 3;
  • 如何使用 ArrayUtils?
猜你喜欢
  • 2019-02-18
  • 2011-03-05
  • 2021-04-17
  • 2011-08-22
  • 1970-01-01
  • 2010-10-03
  • 2023-02-24
  • 1970-01-01
相关资源
最近更新 更多