What is the best way to find nth occurrence of a number in ArrayList?
What I know already?
- To find lastIndexOf the number there is method in List interface, which is implemented in ArrayList class.
- To find first occurence there is indexOf method.
What I was solving?
In a problem there was a list with different numbers and I have to return index of two numbers whose sum is equal to target number.
Ex: List = (1,2,1) & target = 2;
Now 1 + 1 =2
and answer will be index of first 1 and second 1.
Note: I have solved this problem & I need answer to the question at the top. Check Solution
What I did?
public static void main(String[] args)
{
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(1);
int length = list.size();
int firstIndex = list.indexOf(1) + 1;
int secondIndex = firstIndex + list.subList(firstIndex, length).indexOf(1) + 1;
System.out.println(firstIndex);
System.out.println(secondIndex);
}