数组的遍历
485.最大连续1的个数
题解
class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int maxcount=0,count=0;
for (int i =0;i<nums.length;i++){
if(nums[i]==1){
count++;
}else{
maxcount=Math.max(maxcount,count);
count=0;
}
}
maxcount=Math.max(maxcount,count);
return maxcount;
}
}
495.提莫攻击
题解:
方法一:单次扫描
class Solution {
public int findPoisonedDuration(int[] timeSeries, int duration) {
int ans = 0;
int expire = 0;
for (int i =0;i<timeSeries.length;i++){
if(timeSeries[i] >= expire){
ans += duration;//如果当前他正处于未中毒状态,则此时他的中毒持续时间应增加 duration,同时更新本次中毒结束时间 expired 等于 timeSeries[i]+duration;
}else{
ans += timeSeries[i] + duration -expire;
//如果当前他正处于中毒状态,由于中毒状态不可叠加,我们知道上次中毒后结束时间为 expired,本次中毒后结束时间为 timeSeries[i]+duration,因此本次中毒增加的持续中毒时间timeSeries[i]+duration−expired;
}
expire = timeSeries[i] + duration;
}
return ans;
}
}
方法二:中毒时间拉满,再减去重复的时间。
public int findPoisonedDuration(int[] timeSeries, int duration) {
int res = timeSeries.length * duration;
for(int i = 1;i < timeSeries.length;i++){
if(timeSeries[i] - timeSeries[i-1]<duration){
res -= duration - timeSeries[1] - timeSeries[i-1];
}
return res;
}