?題目來(lái)源:
? ? ? ? leetcode題目,網(wǎng)址:2511. 最多可以摧毀的敵人城堡數(shù)目 - 力扣(LeetCode)
解題思路:
? ? ? ?順序遍歷數(shù)組,記錄上一個(gè)我軍城堡和沒有城堡的位置。當(dāng)碰到空位置時(shí),若上一次更新的值為我軍城堡,記錄較大的摧毀數(shù);當(dāng)碰到我軍城堡時(shí),若上一次更新的值為空位置,記錄較大的摧毀數(shù)。
解題代碼:
class Solution {
public int captureForts(int[] forts) {
int res=0;
int lastEmpty=-1;
int lastCommand=-1;
for(int i=0;i<forts.length;i++){
if(forts[i]==-1){
if(lastCommand!=-1 && lastCommand>lastEmpty){
res=Math.max(res,i-lastCommand-1);
}
lastEmpty=i;
}else if(forts[i]==1){
if(lastEmpty!=-1 && lastEmpty>lastCommand){
res=Math.max(res,i-lastEmpty-1);
}
lastCommand=i;
}
}
return res;
}
}
總結(jié):
? ? ? ?注意不能越過我軍城堡去往空地。
? ? ? ? 無(wú)官方題解。
? ? ? ? fort? ? ? ? ?城堡、堡壘文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-641470.html
? ? ? ? capture? ? ? ? 俘獲,采集,拍攝文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-641470.html
到了這里,關(guān)于題目:2511.最多可以摧毀的敵人城堡數(shù)量的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!