Write a method searchInLastN
that implements a linear search but only looks for values in the last positions, determined by the parameter...
X1283: Search in the last n
Write a method searchInLastN
that implements a linear search but only looks for values in the last positions, determined by the parameter lastN
, of the array. If the value is found in the lastN
positions of the array, then it should return the index of the first occurence of the value (first time it appears). If the value is not found, it should return -1.
For example consider an array with 10 positions and these values:
int nums[] = {9, 18, 3, 17, 12, 10, 7, 5, 3, 15 };
A call for searchInLastN(nums, 3, 5)
is a call for search for the number 5 in the last 3 positions of the array. This would check only positions [7], [8], and [9]. The routine would find value 5 at position [7] and thus would return that index.
searchInLastN(nums, 3, 5) -> 7
A second example, a call like this searchInLastN(nums, 2, 7)
would check positions [8] and [9] and return -1 (not found) as the value 7 is not in the last 2 positions.
searchInLastN(nums, 2, 7) -> -1
This should work for arrays of any size. You can assume that the array size is larger than the value in lastN
.
Examples:
searchInLastN({9, 18, 3, 17, 12, 10, 7, 5, 3, 15},3,5) -> 7
searchInLastN({9, 18, 3, 17, 12, 10, 7, 5, 3, 15},2,7) -> -1
searchInLastN({9, 18, 3, 17, 12, 10, 7, 5, 3, 15},10,9) -> 0
searchInLastN({9, 18, 3, 17, 12, 10, 7, 5, 3, 15},10,3) -> 2
Your Answer:
Feedback
Your feedback will appear here when you check your answer.