mochi
mochi

Reputation: 29

Finding the last occurrence of x in the array

I want to find the last occurrence of x(13) in the array which is 6, but my code only finds the first occurrences which is 4, is there a way I can solve this?

/* Application Program */
int[] arr = {9, 12, 2, 8, 13, -8, 13, 9};
int index = lastIndexOf(arr, 13);

if(index != -1)
    System.out.println(index);
else
    System.out.println("not found");


/* Method */
public static int lastIndexOf(int[] arr, int x){
    for(int i = 0; i<arr.length; i++){
        if(arr[i] == x){
            return i;
        }
    }
    return -1;
}

Upvotes: 2

Views: 418

Answers (4)

Mohan k
Mohan k

Reputation: 68

Using java Map based approach.

 public static int lastIndexOfV1(int[] arr, int x) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < arr.length; i++) {
            map.put(arr[i], i);
        }
        return map.get(x);
    }

Upvotes: 1

user8234870
user8234870

Reputation:

you want to find the last occurrence of 13 but you are returning the index in very first match itself.

public static int lastIndexOf(int[] arr, int x){
    for(int i = 0; i<arr.length; i++){
        if(arr[i] == x){
            return i;
        }
    }
    return -1;
}

In order to return the last occurrence you can modify the code and return the most recent index.

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

Upvotes: 0

Sercan
Sercan

Reputation: 5081

Method-1

If you are scanning from the first element to the last element, you should store the result in a variable.

public static int lastIndexOf(int[] arr, int x)
{
    int resultIndex = -1;
         
    for(int i = 0; i < arr.length; i++)
        if(arr[i] == x)
            resultIndex = i;

    return resultIndex;
}
Method-2

If you're scanning from the last element to the first element, you can return the result directly from the method.

public static int lastIndexOf(int[] arr, int x)
{
    for(int i = arr.length - 1 ; i >= 0; --i)
        if(arr[i] == x)
            return i;
    
    return -1;
}

Upvotes: 3

Elliott Frisch
Elliott Frisch

Reputation: 201447

Iterate the array backwards. Like,

public static int lastIndexOf(int[] arr, int x) {
    for (int i = arr.length - 1; i >= 0; i--) {
        if (arr[i] == x) {
            return i;
        }
    }
    return -1;
}

Upvotes: 3

Related Questions