0

線形検索関数を変更して、ベクトル内のターゲットの最後の出現を見つける関数を作成しようとしています。

private int linearSearchRecursive(int[] input, int key,int index) {
    if (index == 0) {
        return -1;
    }
    if (input[index] == key) {
        return index;
    }
    else 
    return linearSearchRecursive(input,key,--index);
}

ヘルパー関数を使用して機能させる方法を考えました...

public static int findLastOccurance(int[] items, int key){
    return linearSearchRecursive(items, key, items.length - 1);
}

または、そのような性質のものですが、再帰性を維持しながら 1 つの関数のみを使用できる簡単な方法があるかどうか疑問に思っていましたか?

4

1 に答える 1

2

簡単ではありませんが、機能は 1 つだけです。

public class Test {

public static int findLastOccuranceRecursive(int[] input, int key, int... optionalIndex) {
    if (optionalIndex.length == 0) {
        optionalIndex = new int[] { input.length - 1 };
    } else if (optionalIndex.length != 1) {
        throw new IllegalArgumentException("size of optionalIndex must be 0 or 1");
    }

    if (optionalIndex[0] == 0) {
        return -1;
    }
    if (input[optionalIndex[0]] == key) {
        return optionalIndex[0];
    } else {
        optionalIndex[0]--;
        return findLastOccuranceRecursive(input, key, optionalIndex);
    }
}

public static int findLastOccuranceIterative(int[] items, int key) {
    for (int i = items.length - 1; i >= 0; i--) {
        if (items[i] == key) {
            return i;
        }
    }
    return -1;
}

public static void main(String[] args) {
    int[] input = { 1, 1, 1, 2, 1, 2, 1, 1 };
    int testRecursive = findLastOccuranceRecursive(input, 2);
    int testIterative = findLastOccuranceIterative(input, 2);
    System.out.println("testRecursive: " + testRecursive + " testIterative: " + testIterative);
}
}
于 2015-10-27T00:14:37.073 に答える