检查数组中是否存在一个范围内的所有值的最佳方法是什么?(爪哇)
我的任务是确定1,2,3中的每一个值。。。n在无序的int数组中。我不确定这是否是最有效的方法,但我创建了一个名为range的int[],它只包含范围[I]中从1到n的所有数字(范围[0]=1,范围[1]=2,等等)。然后我尝试使用containsAll方法检查给定数字的数组是否包含范围数组中的所有数字。然而,当我测试它时,它返回false。我的代码有什么问题,还有什么更有效的方法来解决这个问题
public static boolean hasRange(int [] givenNums, int[] range) {
boolean result = true;
int n = range.length;
for (int i = 1; i <= n; i++) {
if (Arrays.asList(givenNums).containsAll(Arrays.asList(range)) == false) {
result = false;
}
}
return result;
}
(我很确定我应该手动完成这项工作,而不是使用containsAll方法,因此如果有人知道如何用这种方式解决它,那将特别有用!)
对于好奇的人来说,这种方法的含义如下:
public static void checkMatrix(int[][] intMatrix) {
File numberFile = new File("valid3x3") ;
intMatrix= readMatrix(numberFile);
int nSquared = sideLength * sideLength;
int[] values = new int[nSquared];
int[] range = new int[nSquared];
int valCount = 0;
for (int i = 0; i<sideLength; i++) {
for (int j=0; j<sideLength; j++) {
values[valCount] = intMatrix[i][j];
valCount++;
}
}
for (int i=0; i<range.length; i++) {
range[i] = i+1;
}
Boolean valuesThere = hasRange(values, range);
值打印时为假
# 1 楼答案
第一款:
然后是问题。值得称赞的是,列表甚至更好的集合方法是精确的抽象级别:深入细节是不明智的。然而,这正是我们想要的
要知道[1,…,n]范围内的每个元素是否都存在
如果达到n个新数字:返回true
想出更好的名字
# 2 楼答案
这和你想的不一样。它返回一个带有单个元素的
List<int[]>
,它不会将givenNums
中的值框到Integer
并返回List<Integer>
。这就解释了为什么你的方法不起作用使用Java8流,假设您不想对
givens
进行永久排序。如果你不在乎,就去掉copyOf()
:# 3 楼答案
你说你有一个一维数组,对吗? 好的那我想你是在考虑复杂化。 我试着解释另一种方法来检查数组中的所有数字是否都是按数字顺序排列的
例如,数组具有以下值:
首先,你可以订购simpel阵列
完成此操作后,可以在数组中循环并与索引进行比较,如(在方法中):