【发布时间】:2017-05-01 05:30:56
【问题描述】:
编写一个方法,当传递一个整数数组 arr 和一个整数目标时, 返回数组中出现目标的最后一个索引。如果数组为空或数组中不存在目标,则返回 -1。
所以我使用线性搜索来做到这一点。
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;
}}
这是正确的还是正确的方法?
【问题讨论】:
-
不,它要求 last 索引