Write a method that when passed an array of integers arr, and an integer target, returns the last index at which target occurs in the array. Return -1 if the array is null or if target doesn’t exist in the array.
所以我使用线性搜索来做到这一点。
public static void linearSeach(int [] arr, target){
if( arr == null){
return -1;
}
count = 0;
for (int i = 0; i< arr.length; i++){
if( target == arr[i]){
count ++;
}
}
// I cannot return both count and -1 so here is what I thought I should do
if( count >= 0){
return count;
}
else {
return -1;
}}
这是正确的还是正确的方法?
最佳答案
否,您返回的是目标数字在数组中出现的次数。您应该返回上次出现的索引:
if (arr != null) {
for (int i = arr.length - 1; i >= 0; i--){
if (target == arr[i]) {
return i;
}
}
}
return -1;
关于java - 线性搜索查找数组中目标的最后一个索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43714712/