gpt4 book ai didi

java - 向后递归线性搜索

转载 作者:行者123 更新时间:2023-12-02 04:15:35 25 4
gpt4 key购买 nike

我正在尝试编写一个函数,通过修改线性搜索函数来查找 vector 中最后一次出现的目标。

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);
}

或者类似的东西,但想知道是否有一种更简单的方法可以让我只使用一个函数但保持递归性?

最佳答案

并不简单,但只有一个功能:

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);
}
}

关于java - 向后递归线性搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33357005/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com