Reputation:
My job is to write a method named findLastIndex
, this method receives an array and an integer value representing an element of the array. findLastIndex
searches through the array to find the given element and returns the index the last time this element is found in the array (the position of the element closest to the length of the array). In case the element is not found in the array, the method returns -1.
So my current code looks the following:
public static int findLastIndex(int [] nums, int element){
for(int i = 0; i < nums.length; i++){
if(i == element){
return nums[i];
}
}
return -1;
}
But I have no idea how to not return the first time , but to make it return the last times the element was found.
Upvotes: 0
Views: 107
Reputation: 116
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
}
Saw other people gave good answers... figured I would give it a try for fun.
Upvotes: 0
Reputation: 1249
You simply save the (currently) last index while looping through the array:
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;
}
But, maybe the better option is to search from the end of the array:
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;
}
Upvotes: 3