485. Max Consecutive Ones
Der Aufgabentext wird für die gewählte Sprache aus dem Russischen übersetzt. Code bleibt unverändert.
Дан бинарный Array nums, return максимальное количество последовательных единиц в Arrayе.
Beispiel:
Input: nums = [1,1,0,1,1,1]
Output: 3
Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3.
C# Lösung
zugeordnet/originalpublic class Solution {
public int FindMaxConsecutiveOnes(int[] nums) {
int count = 0;
int maxCount = 0;
foreach (int num in nums) {
if (num == 1) {
count += 1;
} else {
maxCount = Math.Max(maxCount, count);
count = 0;
}
}
return Math.Max(maxCount, count);
}
}
C++ Lösung
Auto-Entwurf, vor dem Einreichen prüfen#include <bits/stdc++.h>
using namespace std;
// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
class Solution {
public:
public int FindMaxConsecutiveOnes(vector<int>& nums) {
int count = 0;
int maxCount = 0;
foreach (int num in nums) {
if (num == 1) {
count += 1;
} else {
maxCount = max(maxCount, count);
count = 0;
}
}
return max(maxCount, count);
}
}
Java Lösung
zugeordnet/originalclass Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int count = 0;
int maxCount = 0;
for (int num : nums) {
if (num == 1) {
count += 1;
} else {
maxCount = Math.max(maxCount, count);
count = 0;
}
}
return Math.max(maxCount, count);
}
}
JavaScript Lösung
zugeordnet/originalvar findMaxConsecutiveOnes = function(nums) {
let count = 0
let maxCount = 0
for (let num of nums) {
if (num === 1) {
count += 1
} else {
maxCount = Math.max(maxCount, count)
count = 0
}
}
return Math.max(maxCount, count)
}
Python Lösung
zugeordnet/originalclass Solution:
def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
count = 0
maxCount = 0
for num in nums:
if num == 1:
count += 1
else:
maxCount = max(maxCount, count)
count = 0
return max(maxCount, count)
Go Lösung
zugeordnet/originalfunc findMaxConsecutiveOnes(nums []int) int {
count := 0
maxCount := 0
for _, num := range nums {
if num == 1 {
count++
} else {
if count > maxCount {
maxCount = count
}
count = 0
}
}
if count > maxCount {
maxCount = count
}
return maxCount
}
Algorithm
Поддерживайте счетчик для подсчета единиц и увеличивайте его на 1 при встрече единицы.
Когда встречаете ноль, используйте текущий счетчик единиц для нахождения максимального количества последовательных единиц на данный момент, затем сбросьте счетчик единиц на 0.
В конце return максимальное значение.
😎
Stellen zu dieser Aufgabe
aktive Stellen with overlapping task tags are angezeigt.
Es gibt noch keine aktiven Stellen.