forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_957.java
46 lines (43 loc) · 1.39 KB
/
_957.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
40
41
42
43
44
45
46
package com.fishercoder.solutions;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class _957 {
public static class Solution1 {
public int[] prisonAfterNDays(int[] cells, int N) {
Set<String> prisonStates = new HashSet<>();
boolean hasCycle = false;
int times = 0;
for (int i = 0; i < N; i++) {
int[] next = getNextDay(cells);
String nextDayState = Arrays.toString(next);
if (prisonStates.contains(nextDayState)) {
hasCycle = true;
break;
} else {
prisonStates.add(nextDayState);
times++;
}
cells = next;
}
if (hasCycle) {
N %= times;
for (int i = 0; i < N; i++) {
cells = getNextDay(cells);
}
}
return cells;
}
private int[] getNextDay(int[] cells) {
int[] nextDay = new int[cells.length];
for (int i = 0; i < cells.length; i++) {
if (i == 0 || i == cells.length - 1) {
nextDay[i] = 0;
} else {
nextDay[i] = (cells[i - 1] == cells[i + 1]) ? 1 : 0;
}
}
return nextDay;
}
}
}