繁体   English   中英

基本的Java数组方法

[英]basic java array method

我的工作是编写一个名为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;
}

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

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

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;
}
  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

}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM