依次遍历为数组 forts 中的每个元素,此时我们用 pre 记录数组中前一个为 1 或者 -1 的位置;
假设当前元素 forts}[i] 为 1 或者 -1,即当前位置可能为军队的起点或终点,此时假设 forts}[i] \neq \textit{forts}[\textit{pre}],即此时可以在 i 与 pre 之间可以移动,此时可以摧毁的城堡数目为 i - \textit{pre} - 1,更新当前的最大城堡数目,同时记录新的 pre;
按照上述方法找到最大可以摧毁的城堡数目即可。
代码
[sol1-C++]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution { public: intcaptureForts(vector<int>& forts){ int ans = 0, pre = -1; for (int i = 0; i < forts.size(); i++) { if (forts[i] == 1 || forts[i] == -1) { if (pre >= 0 && forts[i] != forts[pre]) { ans = max(ans, i - pre - 1); } pre = i; } } return ans; } };
[sol1-C#]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
publicclassSolution { publicintCaptureForts(int[] forts) { int n = forts.Length; int ans = 0, pre = -1; for (int i = 0; i < n; i++) { if (forts[i] == 1 || forts[i] == -1) { if (pre >= 0 && forts[i] != forts[pre]) { ans = Math.Max(ans, i - pre - 1); } pre = i; } } return ans; } }
[sol1-C]
1 2 3 4 5 6 7 8 9 10 11 12
intcaptureForts(int* forts, int fortsSize) { int ans = 0, pre = -1; for (int i = 0; i < fortsSize; i++) { if (forts[i] == 1 || forts[i] == -1) { if (pre >= 0 && forts[i] != forts[pre]) { ans = fmax(ans, i - pre - 1); } pre = i; } } return ans; }
[sol1-Java]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution { publicintcaptureForts(int[] forts) { intn= forts.length; intans=0, pre = -1; for (inti=0; i < n; i++) { if (forts[i] == 1 || forts[i] == -1) { if (pre >= 0 && forts[i] != forts[pre]) { ans = Math.max(ans, i - pre - 1); } pre = i; } } return ans; } }
[sol1-Python3]
1 2 3 4 5 6 7 8 9
classSolution: defcaptureForts(self, forts: List[int]) -> int: ans, pre = 0, -1 for i, fort inenumerate(forts): if fort == -1or fort == 1: if pre >= 0and fort != forts[pre]: ans = max(ans, i - pre - 1) pre = i return ans
[sol1-Go]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
funccaptureForts(forts []int)int { ans, pre := 0, -1 for i, fort := range forts { if fort == -1 || fort == 1 { if pre >= 0 && forts[pre] != fort { ans = max(ans, i - pre - 1) } pre = i } } return ans }
funcmax(a int, b int)int { if a > b { return a } return b }
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12
var captureForts = function(forts) { let ans = 0, pre = -1; for (let i = 0; i < forts.length; i++) { if (forts[i] == 1 || forts[i] == -1) { if (pre >= 0 && forts[i] != forts[pre]) { ans = Math.max(ans, i - pre - 1); } pre = i; } } return ans; };
复杂度分析
时间复杂度:O(n),其中 n 表示数组 forts 的长度。在遍历 forts 时,每个元素只会遍历一次,因此时间复杂度为 O(n)。