【发布时间】:2019-02-23 06:41:53
【问题描述】:
假设有一个一维数组test[]={1,2,3} 和一个二维数组arr1[3][5]={{1,2,5,4,3},{3,7,1,4,2},{2,9,7,8,3}}。
输出所需的内容如下:
test is the subset of row 0 of arr1
test is the subset of row 1 of arr1
test is not the subset of row 2 of arr1
这是我目前实现的代码:
class GFG {
public static void main(String args[]) {
int arr1[][] = { { 11, 1, 13, 3, 7 },
{ 11, 1, 17, 7, 3 },
{ 2, 5, 8, 9, 10 } };
int test[] = { 11, 3, 7, 1 };
int m = arr1.length; // rows
int n = test.length;
int o = arr1[0].length; // no. of elements in each row
System.out.println(o); // just for testing if it works
int i = 0;
int j = 0;
int k = 0;
for (i = 0; i < n; i++) {
for (j = 0; j < m && j != m; j++) {
for (k = 0; k < o; k++)
if (test[i] == arr1[j][k])
break;
if (k == o)
System.out.println("test[] is " + "not a subset of arr1 " + j + " row");
else
System.out.println("test[] is " + "subset of arr1 " + j + " row");
}
}
}
}
但我得到的输出是:
我意识到这是 i 循环反复打印它,但在这种情况下我仍然没有得到令人满意的输出。
这里可以做什么? 或者这个问题有很多优化的实现吗? 欢迎提出任何建议。
【问题讨论】:
-
尝试用调试器运行你的程序,看看哪里出错了。
-
一方面,您的
if (k == o)需要一个else -
已经提出了 else 并更新了输出
-
我认为这个问题非常相似/应该可以帮助您找到答案。 stackoverflow.com/questions/16524709/…