LeetCode # 485
Given a binary array, find the maximum number of consecutive 1s in this array.
Example 1:
Input: [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.
Note:
- The input array will only contain 0 and 1.
- The length of input array is a positive integer and will not exceed 10,000
Solution #1 (1ms)
class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int count = 0;
int max = 0;
for(int n : nums){
if(n==1) {
count ++;
if(max < count) max = count;
}
else count = 0;
}
return max;
}
}
Result #1
💡 간단하게 if 조건문을 이용하여 풀었다.
Solution #2
class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int count = 0, max = 0;
for (int n : nums) {
max = Math.max(max,
count = n == 0 ? 0 : count + 1);
}
return max;
}
}
Result #2
💡 Math 함수와 삼항 연산자를 사용하니 코드는 간결해졌다. 하지만 Math.max() 의 시간 복잡도는 O(N).
따라서 시간이 2ms로 증가한 것을 확인할 수 있다.
More Algorithm!
👇👇
github.com/ggujangi/ggu.leet-code
출처 : leetCode
'LeetCode > Easy' 카테고리의 다른 글
[Java] LeetCode 914 : X of a Kind in a Deck of Cards (0) | 2021.04.17 |
---|---|
[Java] LeetCode 1486 : XOR Operation in an Array (0) | 2021.04.17 |
[Java] LeetCode 977 : Squares of a Sorted Array (0) | 2021.03.30 |
[Java] LeetCode 1295 : Find Numbers with Even Number of Digits (0) | 2021.03.30 |
[JAVA] LeetCode Explore - May Week 1 : First Bad Version (0) | 2020.05.03 |