// IMPORT LIBRARY PACKAGES NEEDED BY YOUR PROGRAMimportjava.util.List;importjava.util.LinkedList;importjava.util.Arrays;// SOME CLASSES WITHIN A PACKAGE MAY BE RESTRICTED// DEFINE ANY CLASS AND METHOD NEEDED// CLASS BEGINS, THIS CLASS IS REQUIREDpublicclassSolution{ // METHOD SIGNATURE BEGINS, THIS METHOD IS REQUIREDpublicList<Integer> cellCompete(int[] states,int days) {// WRITE YOUR CODE HEREif (states.length!=8|| days <1) {returnconvertToList(states); }int n =states.length;int prevVal, nextVal;while (days-->0) { prevVal =0; nextVal =0;for (int i =0; i < n; i++) {if (i < n -1) { nextVal = states[i +1]; } elseif (i == n -1) { nextVal =0; }if (nextVal == prevVal) { prevVal = states[i]; states[i] =0; } else { prevVal = states[i]; states[i] =1; } } }returnconvertToList(states); }privateList<Integer> convertToList(int[] arr) {List<Integer> output =newLinkedList<Integer>();for (int a: arr) {output.add(a); }return output; }// METHOD SIGNATURE ENDS}
这个也会TLE
classSolution {publicint[] prisonAfterNDays(int[] cells,int days) {if (cells.length!=8|| days <1) {return cells; }int n =cells.length;int prevVal, nextVal;while (days-->0) { prevVal =0; nextVal =0;for (int i =0; i < n; i++) {if (i ==0|| i == n -1) { prevVal = cells[i]; cells[i] =0;continue; }if (i < n -1) { nextVal = cells[i +1]; } elseif (i == n -1) { nextVal =0; }if (nextVal == prevVal) { prevVal = cells[i]; cells[i] =1; } else { prevVal = cells[i]; cells[i] =0; } } }return cells; }}