-1

can anyone help me find what wrong with this code. I am trying to write a function method that determine the second to the last occurrence of a target in an integer array. Return -1 if not in the array.

public static int findSecondToLast(int [] a, int target) {
    int [] b  = new int[countOfTarget (a,target)];
    int k =0;

    for (int i = 0; i < a.length; i++){
        if  (a[i]==target){
            b[k]=i;
            k++;
            return  b[ countOfTarget (a,target) - 1];
        }
    }

    return -1;
}

public static int countOfTarget (int[]a, int t){
    int count = 0;
    for (int i=0; i < a.length; i++) {
        if (a[i] == t) 
            count++;
    }
    return count;
}
4

3 回答 3

3

尝试将您的代码更改为

public static int findSecondToLast(int[] a, int target)
    {
        int[] b = new int[countOfTarget(a, target)];
        int k = 0;

        for (int i = 0; i < a.length; i++)
        {
            if (a[i] == target)
            {
                b[k] = i;
                k++;
                return b[ countOfTarget(a, target) - 1];
            }
        }
        return -1;
    }

return-1声明必须在外面for loop

于 2013-10-23T01:15:50.720 回答
1

如果您只是以相反的顺序扫描并返回元素的第二次出现,则此问题会容易得多:

public static int findSecondToLast(int[] a, int terget) {
    int firstFound = false;
    for (int i = a.length - 1; i >= 0; --i) {
        if (a[i] == target) {
            if (firstFound) {
                return i;
            }
            firsrFound = true;
        }
    }
    return -1;
}

无需使用该countOfTarget方法,也无需对数组进行三次迭代(这是您的原始代码所做的)。

于 2013-10-23T01:20:41.880 回答
0

您需要将功能更改为以下功能:

public static int findSecondToLast(int [] a, int target)
{
    int prev = -1;
    int last = -1;
    for (int i = 0; i < a.length; i++)
        if  (a[i] == target)
        {
            prev = last;
            last = i;
        }
    return prev;
}
于 2013-10-23T01:19:11.637 回答