-1

例如,如果我想将索引 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;
}
4

2 回答 2

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;
    }
于 2013-09-15T23:25:57.497 回答
0

取第 0 个元素是一个变量,然后从第一个索引开始搜索。如果您找到匹配停止,则一直到数组的末尾并报告未找到匹配项。这可以在线性时间 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 作为参数。

于 2013-09-15T23:30:40.420 回答