user6857832
user6857832

Reputation:

How to get the index of an element in the list if there is an duplicate element

List<List<Integer>> triangle = new ArrayList<List<Integer>>();
    triangle.add(Arrays.asList(75));
    triangle.add(Arrays.asList(64, 94));
    triangle.add(Arrays.asList(82, 47, 82));
    int max = 0;
    int x = 0;
    int y = 0;
    int sum = 75;
    int j = 0;


    for (int i = 1; i < triangle.size() - 1; i++) {
        FOUND: {
            for (j = j; j <= triangle.get(i).size(); j++) {
                x = triangle.get(i).get(j);
                y = triangle.get(i).get(j + 1);
                max = Math.max(x, y);
                int index = triangle.get(i).indexOf(max);
                System.out.println("INDEX: "+index);
                j = index;
                sum += max;
                break FOUND;    
             }
        }
    }
}

Upvotes: 0

Views: 69

Answers (1)

Darshan Mehta
Darshan Mehta

Reputation: 30809

You can use lastIndexOf method to get the last index of that element, e.g.:

int index = triangle.get(i).lastIndexOf(max);
System.out.println("INDEX: "+index);

Here's an exmple of the same.

Upvotes: 1

Related Questions