The problem is to remove every 2nd element until the last one remains. (Assuming the elements are placed in circle)
My program works fine for small values of n but when i use a large value it gives me a java.lang.OutOfMemoryError: Java heap space
message.
Can some help me out as to what I need to do to make my code more efficient and solve this error.
Thank You!
import java.util.*;
public class ArrayLists {
public static void main(String[] args) {
ArrayList myList = new ArrayList();
int n = 23987443;
for (int i = 1; i <= n; i = i + 2) {
myList.add("" + i);
}
Object x = myList.get(myList.size() - 1);
Object y = myList.get(myList.size() - 1);
while (myList.size() != 1) {
if (x == y) {
for (int i = 0; i <= myList.size() - 1; i++) {
myList.remove(i);
}
}
else {
x = y;
for (int i = 1; i <= myList.size() - 1; i++) {
myList.remove(i);
}
}
y = myList.get(myList.size() - 1);
}
System.out.println("Winner:" + myList);
}
}