1

Я пытаюсь выполнить линейный поиск по массиву, где он находит последнее вхождение цели. Я застрял, потому что мой поиск обнаруживает только первое появление цели не последним.Linear Search Recursive Last Occurrence

/** Recursive linear search that finds last occurrence of a target in the array not the first 
* 
* @param items The array 
* @param target the item being searched for 
* @param cur current index 
* @param currentLength The current length of the array 
* @return The position of the last occurrence 
*/ 
public static int lineSearchLast(Object[] items, Object target, int cur, int currentLength){ 
    if(currentLength == items.length+1) 
     return -1; 
    else if (target.equals(items[cur])&& cur < currentLength) 
     return cur; 
    else 
     return lineSearchLast(items, target, cur +1, currentLength); 
} 

public static void main (String[] args){ 
Integer[] numbers5 = {1,2,4,4,4}; 
int myResult = lineSearchLast(numbers5, 4, 0, 5); 
System.out.println(myResult); 
+0

Нужно ли быть рекурсивным? Вы можете упростить вещи, просто перебирая список. –

+0

Я рекомендую вам возвратить 'max (cur, lineSearchLast (items, target, cur +1, currentLength);'. Там 'Math # max', но он возвращает' double', а не 'int', поэтому, возможно, вы хотите/необходимо создать или адаптировать этот метод. –

+1

@DanJMiller или путем перемещения списка от последнего элемента до первого и возврата первого вхождения. –

ответ

1

Вам не нужны два аргумента индекса - один (текущий индекс) должен делать трюк. Кроме того, чтобы убедиться, что вы сначала найдете последний эквивалентный элемент, разумно начинать с обратной стороны и работать вперед.

/** Returns the index of the last occurance of target in items */ 
public static int findLastOccurance(Object[] items, Object target){ 
    return findLastOccurance(items, target, items.length - 1); 
} 

/** Helper method for findLastOccurance(items, target). Recursively finds 
    * the index of the last occurance of target in items[0...cur] 
    */ 
private static int findLastOccurance(Object[] items, Object target, int cur){ 
    if(curr == -1) //We went past the start - missed it. 
     return -1; 
    else if (target.equals(items[cur])) //Found it 
     return cur; 
    else 
     return lineSearchLast(items, target, curr-1); //Work backwards 
} 
+0

Удивительный, спасибо. Имеет смысл сначала начать поиск назад, сделать вещи намного проще – jumpman8947