LC.P2511[最多可以摧毁的敌人城堡数目]

方法一:双指针

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public int captureForts(int[] forts) {
int ans = 0, n = forts.length;
for (int i = 0; i < n; ) {
int j = i + 1;
if (forts[i] != 0) {
while (j < n && forts[j] == 0) ++j;
if (j < n && forts[i] + forts[j] == 0) {
ans = Math.max(ans, j - i - 1);
}
}
i = j;
}
return ans;
}
}
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(1)$