如何在数组中找到max int,而忽略大于第一个值的所有数字?

时间:2017-03-31 04:15:43

标签: java arrays recursion

我正在处理的任务中遇到此问题。我相信问题是该方法永远不会返回负值,但我不确定为什么会这样或如何解决它。 (此外,这必须使用递归来完成,即使这可能是实现它的最糟糕方式。

private static int findMaxOfLessThanFirst(int[] numList, int startIndex, int endIndex, int firstNum) {
    if(startIndex>-1&&startIndex<100){
        if(startIndex==endIndex){
            if(numList[startIndex]<=firstNum){
                return numList[startIndex];
            } else {
                return 222; //number used for testing
            }
        }
        if(numList[startIndex]>=
        findMaxOfLessThanFirst(numList,startIndex+1,endIndex,firstNum) &&
        numList[startIndex]<=firstNum){         
            return numList[startIndex];
        } else {
            return findMaxOfLessThanFirst(numList,startIndex+1,endIndex,firstNum);
        }
    } return 333; //number used for testing
}

目标是返回最大数组中的整数,同时忽略大于numList [0]的所有数字。

1 个答案:

答案 0 :(得分:0)

private static int findMaxOfLessThanFirst(int[] numList, int currentIndex, int len, int currentMax) {
    // when you reach the end of the array, return the currentMax
    if (currentIndex == len - 1) {
        return currentMax;
    }
    int firstElement = numList[0];
    // if the current element we are looking at in this stage of the recursion is greater
    // than the first element, ignore it and recurse on the next element
    if (numList[currentIndex] >= firstElement) {
        return findMaxOfLessThanFirst(numList, currentIndex + 1, len, currentMax);
    }
    int newMax;
    // if none of the previous conditions were true, and this current value is greater than
    // the currentMax, update the currentMax
    if (numList[currentIndex] > currentMax) {
        newMax = numList[currentIndex];
    }
    return findMaxOfLessThanFirst(numList, currentIndex + 1, len, newMax);
}

调用此函数时,将currentMax设置为最小整数值。这样你可以检查最后的返回值,看看你是否确实有一个小于第一个元素的元素。