二维数组中的非重复数

uelo1irk  于 2021-06-30  发布在  Java
关注(0)|答案(3)|浏览(404)

我有我的代码问题,我想找到数组中不重复的数字,但我不知道如何!

1 2
3 4
1 4

例如,在本例中,我希望输出为数字3和2:
我用这个代码得到数组,它就像一个矩阵

for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 2; j++) {
        cam[i][j] = in.nextInt();
    }
}

像这样的东西,用来比较每一个:

for (int i = 1; i <= 3; i++) {            
    if (cam[i][2] != cam[i+1][2]) {
        y = cam[i+1][2];
        break;
    }            
}

更新:下面是完整的代码

int x=0,y=0;
int[][] cam = new int[10][10];

for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 2; j++) {
        cam[i][j] = in.nextInt();
    }
}

for (int i = 1; i <= 3; i++) {          
    if (cam[i][1] != cam[i+1][1]) {
        x = cam[i+1][1];
        break;
}

for (int i = 1; i <= 3; i++) {            
    if (cam[i][2] != cam[i+1][2]) {
        y = cam[i+1][2];
        break;
    }            
}

System.out.println(x+" "+y);
ezykj2lf

ezykj2lf1#

数组索引为0,1,2,…,长度为1。

for (int i = 0; i < cam.length; i++) {
    for (int j = 0; j <= cam[i].length; j++) {
        cam[i][j] = in.nextInt();
    }
}

搜索代码:

for (int i = 0; i < cam.length; i++) {
    for (int j = 0; j <= cam[i].length; j++) {
        int valueAtIJ = cam[i][j];
        boolean found = false;
        ... walk here through cam using valueAtIJ, set found, skip i, j.
        if (!found) {
            ...
        }
    }
}

如果在你的课程中使用alread set/map,那么会有更聪明的解决方案。但是这种for-i2-for-j2回路也可以优化。

knpiaxh1

knpiaxh12#

假设您的代码只在第1列和第2列中查找(第0列中有其他数据吗?):

for (int i = 1; i <= 3; i++) {
    found = false;
    for (int i1 = i + 1; i1 <= 3; i1++) {
        if (cam[i][1] == cam[i1][1]) {
            found = true;
            break;
        }
    }
    if (!found) {
        x = cam[i][1];
    }
}
for (int i = 1; i <= 3; i++) {
    found = false;
    for (int i1 = i + 1; i1 <= 3; i1++) {
        if (cam[i][2] == cam[i1][2]) {
            found = true;
            break;
        }
    }
    if (!found) {
        y = cam[i][2];
    }
}
xwbd5t1u

xwbd5t1u3#

你可以 collect 从这个2d数组中复制一个Map,然后在这个Map上迭代并应用 filter 对于非重复元素:

int[][] arr = {
        {1, 2},
        {3, 4},
        {1, 4}};

Map<Integer, Long> map = Arrays.stream(arr)
        .flatMapToInt(Arrays::stream).boxed()
        .collect(Collectors.groupingBy(
                Integer::intValue, Collectors.counting()));

System.out.println(map); // {1=2, 2=1, 3=1, 4=2}

int[] arr2 = map.entrySet().stream()
        .filter(e -> e.getValue() == 1)
        .mapToInt(Map.Entry::getKey)
        .toArray();

System.out.println(Arrays.toString(arr2)); // [2, 3]

另请参阅:如何有效地查找数组中的重复元素?

相关问题