【问题标题】:Linear seach finding the last index of a target within an array线性搜索查找数组中目标的最后一个索引
【发布时间】: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 索引

标签: java arrays search


【解决方案1】:

不,您返回的是目标数字在数组中出现的次数。您应该返回上次出现的索引:

if (arr != null) {
    for (int i = arr.length - 1; i >= 0; i--){
        if (target == arr[i]) {
            return i;
        }
    }
}
return -1;

【讨论】:

    【解决方案2】:
    public static void linearSeach(int [] arr, target){
        if( arr != null) {      
            int i = arr.length - 1
            while (i>=0){
                if( target == arr[i]){
                     return i;
                } 
                i= i-1              
            }
        }
        return -1;
    }
    

    【讨论】:

      猜你喜欢
      • 2010-11-06
      • 1970-01-01
      • 1970-01-01
      • 2013-02-14
      • 2017-03-06
      • 2011-01-14
      • 1970-01-01
      • 1970-01-01
      • 2022-12-18
      相关资源
      最近更新 更多