Fun*_*zin 5 java arrays multidimensional-array
解决问题的标准:将复杂度降低为线性。我只能使用集合类型为Comparable的数组。重复元素应被允许。
我的关注点:我的代码段(获取常见元素(字符串)的方法):
//Comparable[] items1 = {'a', 'c', 'd', 'e', 'f','d',};
//Comparable[] items2 = {'a', 'c','d', 'e', 'd','f', 'g', 'h'};
//Comparable[] items3 = {'a', 'c','d', 'e','d', 'g'};
//Comparable[][] items = {items1, items2, items3};
public static ArrayList<Comparable> findCommonElements(Comparable items[][]) {
int i, j=0;
int rows = items.length;
ArrayList common = new ArrayList();
int []x = new int[rows]; //
for(i=0; i<items.length; i++) {
// here is where I have the problem. It doesn't loop over the entire list in first row. Therefore, I can only get the first 3.
Comparable value = collections[0][x[0]];// obtain the first row.
for(j=0;j<items[i].length; j++) {
if(items[i][j].compareTo(value)==0) {// compare the values.
common.add(value);
x[0]++;
}
}
}
return common;
}
Run Code Online (Sandbox Code Playgroud)
我的输出:
[a,c,d]
正确的输出:
[a,c,d,e,d]