如果我想比较索引0和索引1,2和3,那怎么可能?
boolean iftrue = false;
for (int i = 0; i < array.length - 1; i++) {
for (int j = 0; j < i; j++) {
if (IntValue(array[j]) == IntValue(array[i + j])) {
iftrue = true;
}
}
}
return iftrue;
}
答案 0 :(得分:0)
只是将Sotirios的建议放入代码中......回想一下,他建议你保存第一个元素,然后比较其他元素。
public boolean sameAsFirstElem(int[] array) {
boolean isEqual = false;
int firstElem = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] == firstElem) {
return true;
}
}
return isEqual;
}
答案 1 :(得分:0)
取第0个元素是变量,继续从第1个索引开始搜索。如果你发现匹配停止,则一直到阵列的末尾并报告未找到的匹配。这可以在线性时间O(N)中完成,其中N是阵列的大小。无需具有两个循环,因此将时间复杂度增加到O(N ^ 2)
boolean sameAsFirstElem(Object[] array) {
boolean isEqual = false; //Assume match will not be there, if we come across any,
// we will set it to true
int firstElement = IntValue(array[0]);
for (int i = 1; i < array.length; i++) {
if (IntValue(array[i]) == firstElement) {
isEqual = true; //Indicating that match has found
}
}
return isEqual;
}
我假设IntValue(Object)返回int,因此返回int firstElement
,并将Object作为参数。