此代码在没有 流 的 Java 7 中工作。该方法与使用binarySearch 方法相同。接受参差不齐的二维数组和无限数量的元素进行搜索。
还有loops,这个任务用rows比用columns更容易解决。
public static void main(String[] args) {
int[][] arr = {{1, 2, 3}, {4, 5}, {6, 7, 8}};
System.out.println(sameRow(arr, 4, 5)); // true
System.out.println(sameCol(arr, 3, 8)); // true
System.out.println(sameCol(arr, 2, 5, 7)); // true
}
/**
* @param arr 2d array.
* @param elements 1d array of elements to search for.
* @return whether any column of a 2d array contains all elements from a 1d array.
*/
public static boolean sameCol(int[][] arr, int... elements) {
// iterate through the columns
for (int i = 0; ; i++) {
// take an array of values from the column, if any
int[] col = new int[arr.length];
// column counter
int j = 0;
// iterate through the rows
for (int[] row : arr)
// take those rows where this column is present
if (row.length > i)
// take the value from the column
// and increase the counter
col[j++] = row[i];
// until the columns are still present
if (j == 0) break;
// if this column contains all the search elements
if (containsAll(Arrays.copyOf(col, j), elements))
return true;
}
return false;
}
/**
* @param arr 2d array.
* @param elements 1d array of elements to search for.
* @return whether any row of a 2d array contains all elements from a 1d array.
*/
public static boolean sameRow(int[][] arr, int... elements) {
for (int[] row : arr)
if (containsAll(row, elements))
return true;
return false;
}
/**
* @param a first array.
* @param b second array.
* @return whether the first array contains all elements from the second array.
*/
public static boolean containsAll(int[] a, int[] b) {
for (int i : b)
if (Arrays.binarySearch(a, i) < 0)
return false;
return true;
}