java - JAVA - 比较两个数组并创建一个仅包含第一个唯一值的新数组
问题描述
我必须使用以下标准解决一个练习:
比较两个数组:
int[] a1 = {1, 3, 7, 8, 2, 7, 9, 11};
int[] a2 = {3, 8, 7, 5, 13, 5, 12};
array
int[]
仅使用第一个数组中的唯一值创建一个新的。结果应如下所示:int[] result = {1,2,9,11};
注意:我不允许使用ArrayList
或Arrays
类来解决此任务。
我正在使用以下代码,但填充循环的逻辑不正确,因为它引发了越界异常。
public static int[] removeDups(int[] a1, int[] a2) {
//count the number of duplicate values found in the first array
int dups = 0;
for (int i = 0; i < a1.length; i++) {
for (int j = 0; j < a2.length; j++) {
if (a1[i] == a2[j]) {
dups++;
}
}
}
//to find the size of the new array subtract the counter from the length of the first array
int size = a1.length - dups;
//create the size of the new array
int[] result = new int[size];
//populate the new array with the unique values
for (int i = 0; i < a1.length; i++) {
int count = 0;
for (int j = 0; j < a2.length; j++) {
if (a1[i] != a2[j]) {
count++;
if (count < 2) {
result[i] = a1[i];
}
}
}
}
return result;
}
我也很想用一个潜在的循环(学习目的)来解决这个问题。
解决方案
我提供以下解决方案。
- 遍历第一个数组,找出最小值和最大值。
- 创建长度为max-min+1 的临时数组(您可以使用max + 1作为长度,但是当您有值(例如从 100k 开始)时,它可能会产生开销)。
- 迭代第一个数组并标记临时数组中存在的值。
- 遍历第二个数组并取消标记临时数组中存在的值。
- 将临时数组中的所有标记值放入结果数组中。
代码:
public static int[] getUnique(int[] one, int[] two) {
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for (int i = 0; i < one.length; i++) {
min = one[i] < min ? one[i] : min;
max = one[i] > max ? one[i] : max;
}
int totalUnique = 0;
boolean[] tmp = new boolean[max - min + 1];
for (int i = 0; i < one.length; i++) {
int offs = one[i] - min;
totalUnique += tmp[offs] ? 0 : 1;
tmp[offs] = true;
}
for (int i = 0; i < two.length; i++) {
int offs = two[i] - min;
if (offs < 0 || offs >= tmp.length)
continue;
if (tmp[offs])
totalUnique--;
tmp[offs] = false;
}
int[] res = new int[totalUnique];
for (int i = 0, j = 0; i < tmp.length; i++)
if (tmp[i])
res[j++] = i + min;
return res;
}
推荐阅读
- r - 在 R 中的多列中过滤值
- react-native - React Native with Expo:如何使用 .env.local 配置文件?
- python - 控制在第二次迭代中跳过该函数。为什么?
- python - Python 3 字符串是 Unicode 字符串,而不是字节数组
- rust - 在创建该类型的线程局部变量的闭包中“使用来自外部函数的类型变量”
- ios - 使用 Swift 将身份验证凭据添加到 iOS 上的钥匙串
- css - textarea white-space nowrap 结合 readonly
- octave - Octave中的@符号是什么?
- linux - 使用现有的 docker 镜像创建新的 Docker 镜像
- node.js - 在 Microsoft Luis 中,如何为实体数组建模?