【问题标题】:Removing duplicates with restrictions删除有限制的重复项
【发布时间】:2014-02-09 06:53:46
【问题描述】:

我被要求为实验室做这个问题,即从用户那里获取一个整数数组,然后删除所有重复项,最后以相同的顺序返回数组。我们被限制使用 Hashsets 和其他与集合相关的想法。没有理由对列表进行排序,因为它必须是原始顺序。谁能给我一些正确方向的提示或指示,我一直在使用其他一些已经回答的问题以寻求帮助。这是我目前所拥有的:

public class Q3C {
    public static void main() {
        System.out.println("Enter your numbers please: ");
        Scanner numbers = new Scanner(System.in);
        String nums = numbers.nextLine();

        String[] parts = nums.split(" ");//
        int[] n1 = new int[parts.length];//
        for (int n = 0; n < parts.length; n++) {
            n1[n] = Integer.parseInt(parts[n]);
        }

    }

我正在考虑创建另一个方法,称为 removeDuplicates 并将数组发送给它,然后它将通过它,检查每个索引是否有其他重复项并将所有重复项设置为下一个索引值。我就是无法理解。任何帮助深表感谢。

【问题讨论】:

标签: java arrays


【解决方案1】:

这里只使用数组(没有集合)的结果:

int[] input = {1, 3, 4, 1, 2, 2, 4, 5, 6, 6};

int[] result = new int[input.length];
int resultSize = 0;

for (int anInput : input) {
    boolean found = false;
    for (int j = 0; j < resultSize; j++) {
        if (anInput == result[j]) { // already exists
            found = true;
            break;
        }
    }
    if (!found) { // add
        result[resultSize++] = anInput;
    }
}

// copy to new result only real values
int[] newResult = new int[resultSize];
System.arraycopy(result, 0, newResult, 0 , resultSize);

System.out.println("result = " + Arrays.toString(newResult));

结果是:

result = [1, 3, 4, 2, 5, 6]

【讨论】:

  • 非常感谢。我使用了你的一些代码,尤其是复制部分。
猜你喜欢
  • 1970-01-01
  • 2020-06-03
  • 2018-02-24
  • 1970-01-01
  • 2015-03-19
  • 1970-01-01
  • 2017-12-10
  • 2014-08-26
  • 2023-03-20
相关资源
最近更新 更多