gpt4 book ai didi

java - 从数组中删除重复项

转载 作者:搜寻专家 更新时间:2023-11-01 01:21:29 27 4
gpt4 key购买 nike

<分区>

enter image description here

我正在处理我的数据结构书中的以下问题。我已经按照本文的建议提出了解决方案。我基本上找到了所有重复项并将它们标记为任意数字,例如 666,然后将它们从数组中删除。

我想问大家的问题是 - 我的解决方案是否与文字建议的完全一致?- 还有什么是解决这个问题更有效的方法?

这里是完整的代码(查看 nodups 方法以查看我的解决方案)

public class HighArray {

private long[] a;
private int nElems;

public HighArray(int max) {

a = new long[max];
nElems = 0;
}

public boolean find(long searchKey) {
int j;
for (j = 0; j < nElems; j++)
if (a[j] == searchKey)
break;

if (j == nElems) {
return false;
}

else {
return true;
}
}

public void insert(long value) {

a[nElems] = value;
nElems++;
}

public void noDups() {
int i = 0;
long compareKey;

while (i < nElems) {

compareKey = a[i];

for (int j = 0; j < nElems; j++) {
if (j != i && a[j] != 666) {
if (a[j] == compareKey) {
a[j] = 666;
}
}
j++;
}

i++;
}

for (int k = 0; k < nElems; k++) {
if (a[k] == 666) {
delete(a[k]);
}
}

}

public boolean delete(long value) {

int j;
for (j = 0; j < nElems; j++)
if (a[j] == value)
break;

if (j == nElems) {
return false;
}

else {
for (int k = j; k < nElems - 1; k++)
a[k] = a[k + 1];
nElems--;
return true;
}
}

public long removeMax() {

if (nElems != 0) {
long maxValue = a[0];

for (int i = 0; i < nElems; i++) {
if (a[i] > maxValue)
maxValue = a[i];
}

delete(maxValue);
return maxValue;
}

else {
return -1;
}
}

public void display() {

for (int i = 0; i < nElems; i++) {
System.out.println(a[i]);
}
}

}

下面的类有main方法。

public class HighArrayApp {

public static void main(String[] args) {

HighArray arr = new HighArray(100);

arr.insert(2);
arr.insert(2);
arr.insert(3);
arr.insert(4);
arr.insert(4);
arr.insert(5);

arr.display();

arr.noDups();

System.out.println("-------------------------");

arr.display();

}

}

我非常感谢任何建议,并且我愿意接受各种尝试更有效算法来解决这个问题的方法。

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com