-
Notifications
You must be signed in to change notification settings - Fork 12
/
prisonAfterNDays.java
39 lines (38 loc) · 1.03 KB
/
prisonAfterNDays.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class Solution {
/*
prison state repeating after a certian number of iterations.
*/
public int[] prisonAfterNDays(int[] cells, int N) {
HashSet<String> set = new HashSet<>();
int times = 0;
boolean flag = false;
for (int i=0; i<N; i++) {
int[] nextArray = nextDays(cells);
String arrString = Arrays.toString(nextArray);
if (!set.contains(arrString)) {
set.add(arrString);
times++;
} else {
flag = true;
break;
}
cells = nextArray;
}
if (flag) {
N = N%times;
for (int i=0; i<N; i++) {
cells = nextDays(cells);
}
}
return cells;
}
public int[] nextDays(int[] cells) {
int[] res = new int[cells.length];
for(int i=1; i<cells.length -1; i++){
if (cells[i-1] == cells[i+1]) {
res[i] = 1;
}
}
return res;
}
}