일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |
Tags
- 프로그래머스
- 경력 개발자
- 용인세브란스병원
- 갑상선암
- 알고리즘
- MYSQL
- 동위원소치료
- 월간 코드 챌린지 시즌1
- 백준알고리즘
- 수술
- Android Compose
- Compose
- 카페
- 안드로이드
- leetcode
- java
- 정렬 알고리즘
- 방사성동위원소치료
- 림프절전이
- 객체
- 방사성 동위원소 치료
- 맛집
- 입원
- 갑상선암용인세브란스
- Android
- firebase
- 저요오드식
- 폐CT
- 전이
- 임파선전이
Archives
- Today
- Total
새우버거의 개발 블로그
[Java] LeetCode 485 : Max Consecutive Ones 본문
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
'알고리즘 > LeetCode' 카테고리의 다른 글
[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 |