Linear Search for Last Occurrence
The findFirst method, shown below, performs a linear search to find the first occurrence of a target value in an integer array.
public static int findFirst(int[] arr, int target) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == target) {
return i;
}
}
return -1;
}
Which of the following code segments, when used as the body of a method, correctly finds the index of the last occurrence of target in arr? If target is not found, the method should return -1.
int lastIndex = -1; for (int i = 0; i < arr.length; i++) { if (arr[i] == target) { lastIndex = arr.length - 1; } } return lastIndex;
for (int i = 0; i < arr.length; i++) { if (arr[i] == target) { return arr.length - 1 - i; } } return -1;
for (int i = arr.length - 1; i >= 0; i–) { if (arr[i] == target) { return i; } } return -1;
for (int i = arr.length; i > 0; i–) { if (arr[i] == target) { return i; } } return -1;
Question Leaderboard
Not enough data yet to show leaderboard.
