gpt4 book ai didi

Java - 合并两个数组而不重复(不允许使用库)

转载 作者:搜寻专家 更新时间:2023-11-01 01:50:30 25 4
gpt4 key购买 nike

需要有关编程问题的帮助。

必须使用 Java。不能使用任何库(Arraylist 等)。

int[] a = {1, 2, 3, 4, 8, 5, 7, 9, 6, 0}
int[] b = {0, 2, 11, 12, 5, 6, 8}

必须创建一个引用这两个数组的对象,该方法将它们合并在一起、删除重复项并对它们进行排序。

到目前为止,这是我的排序。尽管很难合并两个数组并删除重复项。

int lastPos;
int index;
int temp;

for(lastPos = a.length - 1; lastPos >= 0; lastPos--) {
for(index = 0; index <= lastPos - 1; index++) {
if(a[index] > a[index+1]) {
temp = a[index];
a[index] = a[index+1];
a[index+1] = temp;
}
}
}

最佳答案

a method that merges them together, removes duplicates, and sorts them.

我建议您将其分解为辅助方法(并稍微调整操作顺序)。第一步,合并两个数组。类似的东西,

static int[] mergeArrays(int[] a, int[] b) {
int[] c = new int[a.length + b.length];
for (int i = 0; i < a.length; i++) {
c[i] = a[i];
}
for (int i = 0; i < b.length; i++) {
c[a.length + i] = b[i];
}
return c;
}

第 2 步,对新数组进行排序(您现有的排序算法没问题)。喜欢,

static void sortArray(int[] a) {
for (int lastPos = a.length - 1; lastPos >= 0; lastPos--) {
for (int index = 0; index <= lastPos - 1; index++) {
if (a[index] > a[index + 1]) {
int temp = a[index];
a[index] = a[index + 1];
a[index + 1] = temp;
}
}
}
}

最后,删除重复项。第 3a 步,计算 unique 值。假设它们是唯一的,并通过计算相邻(和相等)的值来递减。喜欢,

static int countUniqueValues(int[] c) {
int unique = c.length;
for (int i = 0; i < c.length; i++) {
while (i + 1 < c.length && c[i] == c[i + 1]) {
i++;
unique--;
}
}
return unique;
}

然后是第 3b 步,获取唯一计数并使用前面的方法构建结果。喜欢,

public static int[] mergeDedupSort(int[] a, int[] b) {
int[] c = mergeArrays(a, b);
sortArray(c);
int unique = countUniqueValues(c);
int[] d = new int[unique];
int p = 0;
for (int i = 0; i < c.length; i++) {
d[p++] = c[i];
while (i + 1 < c.length && c[i] == c[i + 1]) {
i++;
}
}
return d;
}

然后你可以用你的数组来测试它

public static void main(String[] args) {
int[] a = { 1, 2, 3, 4, 8, 5, 7, 9, 6, 0 };
int[] b = { 0, 2, 11, 12, 5, 6, 8 };
int[] c = mergeDedupSort(a, b);
System.out.println(Arrays.toString(c));
}

我明白了

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12]

关于Java - 合并两个数组而不重复(不允许使用库),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35329907/

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