2210 - Count Hills and Valleys in an Array
info
- 문제 보기: 2210 - Count Hills and Valleys in an Array
- 소요 시간: 11분 44초
- 풀이 언어:
java
- 체감 난이도: 2️⃣~3️⃣ (2.3)
- 리뷰 횟수: ✅
풀이 키워드
스포주의
슬라이딩 윈도우
풀이 코드
info
- 메모리: 41670 KB
- 시간: 1 ms
class Solution {
public int countHillValley(int[] nums) {
// compress adjacent equal values into one value
List<Integer> numsList = new ArrayList<>();
numsList.add(nums[0]);
for (int i = 1; i < nums.length; ++i) {
if (nums[i-1] != nums[i]) numsList.add(nums[i]);
}
// size 3 sliding window
int ans = 0;
for (int i = 1; i < numsList.size()-1; ++i) {
int a = numsList.get(i-1);
int b = numsList.get(i);
int c = numsList.get(i+1);
if (a < b && c < b) ++ans; // hill
if (a > b && c > b) ++ans; // valley
}
return ans;
}
}
풀이 해설
- 원본 리스트에서 같은 값끼리 인접되어있으면 한 값으로 뭉친다.
- 다 뭉친 리스트에서 크기 3으로 슬라이딩 윈도우를 돌린다.
- hill 또는 valley 조건에 부합할 경우 카운터를 증가시킨다.
메모
- 한 값으로 뭉치는 처리만 약간의 발상 필요