java - 线性搜索查找数组中目标的最后一个索引

标签 java arrays search

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/

相关文章:

java - Java如何存储空值?

javascript - Highcharts 返回错误 #15

php - 如何返回基于日期和随机的颜色值?

javascript - 创建一个下拉搜索表单

java.lang.NullPointerException : uriString

java - Apache HTTP 组件大小限制响应?

c++ - 在点数组中找到最小值的算法

search - 如何在 magento 中将搜索结果页面从 3 列更改为 1 列?

java - Hadoop 自定义输入格式

c - opendir 在 C 语言上无法获取缓冲区 char * 的内容?