java - 确定两个元素是否位于二维数组的同一行或同一列中的最快方法是什么?
问题描述
作为我的一个程序的一部分,我正在尝试检查二维数组中的两个元素是否属于同一行或同一列。我知道可能有很多方法可以解决这个问题,主要是循环和遍历数组,但我只是想知道:有没有快速的方法来确定这一点?
假设我有一个看起来像{{1, 2}, {3, 4}, {5, 6}}
. 是否有任何快速的方法来确定它1
并2
属于同一行?几乎可以在 if 语句中将其评估为“如果 item 与 itemx
属于同一行y
,则这样做等等”?如果没有,那么最快的方法是什么?
解决方案
使用行比使用列更容易解决此任务。你可以使用binarySearch
方法。
此解决方案还适用于参差不齐的二维数组和无限数量的元素进行搜索。
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
}
/**
* @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) {
return IntStream
// iterate through the columns
.iterate(0, i -> i + 1)
// take an array of values from the column, if any
.mapToObj(i -> Arrays
// iterate through the rows
.stream(arr)
// take those rows where this column is present
.filter(row -> row.length > i)
// take the value from the column
.mapToInt(row -> row[i])
// int[] - column
.toArray())
// until the columns are still present
.takeWhile(col -> col.length > 0)
// whether any column contains all the search elements
.anyMatch(col -> containsAll(col, elements));
}
/**
* @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) {
return Arrays.stream(arr).anyMatch(row -> containsAll(row, elements));
}
/**
* @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) {
return Arrays.stream(b).allMatch(i -> Arrays.binarySearch(a, i) > -1);
}
推荐阅读
- php - PHP继承 - 具有子属性的父函数
- c# - 获取音频样本值
- java - 将项目添加到列表时出现 java.lang.UnsupportedOperationException
- excel - 复制多个选择
- azure - Azure ADF @replace 表达式如何转义 \ 字符
- ruby-on-rails - 尝试在弹性 beantalk 上部署 rails 应用程序时缺少模块
- ckeditor4.x - 我如何使用 InsertHtml?
- android - 启用缩小时处理任务时出现异常
- matlab - 如何在MATLAB中找到矩阵中具有相同值的元素的行索引?
- android - Admob 广告页面浏览量远高于平板电脑上的展示次数