将二维数组中每一行的空元素移动到该行的末尾 [英] Move null elements of each row in a 2D array to the end of that row

查看:78
本文介绍了将二维数组中每一行的空元素移动到该行的末尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个看起来像这样的二维数组:

Let's say I have a 2d array which looks like this:

[[O, X, null, O, O, null, null], [null, null, O, null, null, O, O]]

我希望它看起来像这样:

And I want it to look like this:

[[O, X, O, O, null, null, null], [O, O, O, null, null, null, null]]

我试过了,但它不起作用:

I tried this, but it's not working:

String[][] a = new String[row][col];
String[][] b = new String[row][col];

for (int i = 0; i < a.length; i++) {
    for (int j = 0; j < a.length; j++) {
        if (a[i][j] != null) {
            a[i][j] = b[i][j];
        } else {
            b[i][j] = a[i][j + 1];
        }
    }
}

推荐答案

解决问题的几点

  • 您需要使用 a[i].length 进行内循环
  • a[i][j] = b[i][j];这里你需要在b中赋值a
  • 您需要为 b 2D 数组的每一行使用计数器索引,并且每当发现非空值时,在存储后增加此值,其余索引默认为空值.
  • You need to use a[i].length for inner loop
  • a[i][j] = b[i][j]; here you need to assign a value in b
  • You need to use a counter index for b 2D array's every row and whenever found not-null increment this after storing and remaining index are by defult null.
for (int i = 0; i < a.length; i++) {
  int indNew = 0; // Index for every row
  for (int j = 0; j < a[i].length; j++) {
    if (a[i][j] != null) {
      b[i][indNew] = a[i][j]; // store not null value
      indNew++;  // increase after storing
    }
  }
}

这篇关于将二维数组中每一行的空元素移动到该行的末尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆