【问题标题】:basic java array method基本的java数组方法
【发布时间】:2016-01-23 17:36:17
【问题描述】:

我的工作是编写一个名为findLastIndex 的方法,该方法接收一个数组和一个表示数组元素的整数值。 findLastIndex 在数组中搜索给定元素,并返回最后一次在数组中找到该元素时的索引(最接近数组长度的元素的位置)。如果在数组中没有找到该元素,则该方法返回 -1。

所以我当前的代码如下所示:

public static int findLastIndex(int [] nums, int element){
    for(int i = 0; i < nums.length; i++){
        if(i == element){
            return nums[i];
        }
    }
    return -1;
}

但我不知道如何不返回第一次,而是让它返回最后一次找到元素。

【问题讨论】:

  • 假设我给你一本 1000 页的书,我要求你找到出现“你好”这个词的最后一页。你从哪里开始寻找?第一页?

标签: java arrays


【解决方案1】:

您只需在遍历数组时保存(当前)最后一个索引:

public static int findLastIndex(int [] nums, int element){
    int lastIndex = -1
    for(int i = 0; i < nums.length; i++){
        if(nums[i] == element){
            lastIndex = i;
        }
    }
    return lastIndex;
}

但是,也许更好的选择是从数组的末尾开始搜索:

public static int findLastIndex(int [] nums, int element){
    for(int i = nums.length - 1; i >= 0; i--){
        if(nums[i] == element){
            return i;
        }
    }
    return -1;
}

【讨论】:

    【解决方案2】:
      public static int findLastIndex(int [] nums, int element){
           int count = 0; //counts the iterations of the enhanced for loop
           int index = -1;//stores the index that the element is currently in
    
      for(int x : nums){//enhanced for loop
           if(x==element){index=count;}//if element is found in the array it stores the index and will override it if it is found again
           count++;//counts iterations
      }
      return index;//returns the index
    

    }

    看到其他人给出了很好的答案......我想我会试试看。

    【讨论】:

      猜你喜欢
      • 2016-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-02
      • 1970-01-01
      相关资源
      最近更新 更多