
Description
주어진 배열에서 산 모형의 아래 조건을 만족하는 유효한 배열인지 여부를 반환하는 문제입니다.
Given an array of integers arr, return true if and only if it is a valid mountain array.
Recall that arr is a mountain array if and only if:
- arr.length >= 3
- There exists some i with 0 < i < arr.length - 1 such that:
- arr[0] < arr[1] < ... < arr[i - 1] < arr[i]
- arr[i] > arr[i + 1] > ... > arr[arr.length - 1]
Example 1:
Input: arr = [2,1]
Output: false
Example 2:
Input: arr = [3,5,5]
Output: false
Example 3:
Input: arr = [0,3,2,1]
Output: true
Solution 1. One Pass
public boolean validMountainArray (int[] arr) {
if (arr == null || arr.length < 3) { // edge case
return false;
}
boolean isAsc = true; //상승여부
for (int i = 1; i < arr.length; i++) {
if (isAsc) {
if (arr[i - 1] > arr[i]) {
if (i == 1) { // 처음부터 하강이면 탈락
return false;
} else {
isAsc = false; // 하강 전환
}
} else if (arr[i - 1] == arr[i]) { // 상승때 같은 경우 false
return false;
}
} else { //하강
if (arr[i - 1] <= arr[i]) { // 하강시 뒷숫자가 크거나 같으면 false
return false;
}
}
}
return isAsc? false: true; //하강없이 끝나면 산이 아니니 false 아니면 true;
}
One Pass 솔루션으로 조건을 체크해나가며 유효한 배열인지 확인합니다.
Reference
Valid Mountain Array - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
'알고리즘 > LeetCode' 카테고리의 다른 글
[LeetCode] 203. Remove Linked List Elements - 문제풀이 (0) | 2022.01.25 |
---|---|
[LeetCode] 242. Valid Anagram - 문제풀이 (0) | 2022.01.25 |
[LeetCode] 520. Detect Capital - 문제풀이 (0) | 2022.01.25 |
[LeetCode] 383. Ransom Note - 문제풀이 (0) | 2022.01.24 |
[LeetCode] 387. First Unique Character in a String - 문제풀이 (0) | 2022.01.23 |