h******o 发帖数: 334 | 1 Java 有一个2D array: int[][] array; 我想把这个2D array的每个column导入到一个
新的1D array, 下面的方法不知道问题在哪里? 多谢!
int[] column = new int[array.length];
for (int c = 0; c < array[0].length; c++) {
for (int i = 0; i < array.length; i++) {
column[i] = array[i][c];
}
} |
l******t 发帖数: 55733 | 2 这个题看不懂。现在column存的是最后一列的值? |
h******o 发帖数: 334 | 3 谢谢回复!
我想把每一列的值存入一个1D array,这样循环存入。不知道能不能直接把2D array的
每列的值通过index直接存入一个新的1D array?
【在 l******t 的大作中提到】 : 这个题看不懂。现在column存的是最后一列的值?
|
l******t 发帖数: 55733 | 4
现在你前面存的后面就覆盖了?
【在 h******o 的大作中提到】 : 谢谢回复! : 我想把每一列的值存入一个1D array,这样循环存入。不知道能不能直接把2D array的 : 每列的值通过index直接存入一个新的1D array?
|
h******o 发帖数: 334 | 5 怎样才能不覆盖前面存?我想每一列存后,就search 一个数据。完整的code如下:
Write a binary search method, which gets a 2D array and a query as arguments
and returns the number of times that the query occurs in the array. The 2D
array is sorted by columns but not by row.
public static int count(int[][] array, int query) {
int searchTotal = 0;
//iterate each 2D array' column
for (int c=0; c < array[0].length; c++){
searchTotal += biSearch(array, query, c);
}
return searchTotal;
}
private static int biSearch(int[][] array, int searchItem, int colIndex) {
// create a 1D array to hold the entries of 2D array's column
int[] column = new int[array.length];
int count =0;
int low = 0;
int high = column.length - 1;
// put 2D array's column into 1D array
for (int i = 0; i < array.length; i++){
column[i] = array[i][colIndex];
}
// binary search on column array
while (low <= high) {
int mid = low + (high - low) / 2;
if (column[mid] == searchItem) {
count = 1;
int temp = mid;
//continue search the searchItem next to the current found item
while ((temp > 0) && column[temp - 1] == searchItem) {
temp--;
count++;
}
temp = mid;
while (temp < column.length - 1 && column[temp + 1] ==
searchItem) {
temp++;
count++;
}
} else if (column[mid] < searchItem) {
low = mid + 1;
} else if (column[mid] > searchItem) {
high = mid - 1;
}
}
return count;
}
【在 l******t 的大作中提到】 : : 现在你前面存的后面就覆盖了?
|
l******t 发帖数: 55733 | 6 题我都看不明白。number of times?那先对分找到然后前后找?这个2d array等宽?
你可以直接写一个1d坐标到2d坐标(按列算的)的map然后再对分。
大意啊,
total = r * c
x = n / r
y = n % r
然后1 to total对分,每次把对分点n换成x,y就行了。找到了前后再slide,也是1d到
2d转换了 |
h******o 发帖数: 334 | 7 多谢, 我要想想你说的怎么做。新手学java 的数据结构,很费劲。
【在 l******t 的大作中提到】 : 题我都看不明白。number of times?那先对分找到然后前后找?这个2d array等宽? : 你可以直接写一个1d坐标到2d坐标(按列算的)的map然后再对分。 : 大意啊, : total = r * c : x = n / r : y = n % r : 然后1 to total对分,每次把对分点n换成x,y就行了。找到了前后再slide,也是1d到 : 2d转换了
|