LeetCode/Easy
[Java] LeetCode 485 : Max Consecutive Ones
새우버거♬
2021. 3. 30. 03:21
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
ggujangi/ggu.leet-code
LeetCode, Java. Contribute to ggujangi/ggu.leet-code development by creating an account on GitHub.
github.com
출처 : leetCode