반응형
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
Constraints:
- 1 <= arr.length <= 104
- 0 <= arr[i] <= 104
class Solution {
public boolean validMountainArray(int[] arr) {
if (arr.length<3)
return false;
int len = arr.length;
int i = 0;
// 첫번째 값을 증가시켜준다
while (i+1 < len && arr[i]<arr[i+1])
i++;
//시작 또는 끝 문 문자가 카운터와 동일 해야한다
if (i==0 || i==len-1)
return false;
// 배열이 줄어드는 동안 배열 증가
// 마지막 카운터 인덱스 시작
while (i+1 < len && arr[i]>arr[i+1])
i++;
// 길이와 같은 경우 반환
return i == len-1;
}
}
출처: https://leetcode.com/explore/learn/card/fun-with-arrays/527/searching-for-items-in-an-array/3251/
'알고리즘' 카테고리의 다른 글
[Leetcode] Find Numbers with Even Number of Digits (0) | 2021.09.12 |
---|---|
[Leetcode]Max Consecutive Ones (0) | 2021.09.09 |
[LeetCode]Find All Numbers Disappeared in an Array (0) | 2021.09.06 |
[leetcode]Replace Elements with Greatest Element on Right Side (0) | 2021.07.27 |
Check If N and Its Double Exist (0) | 2021.07.19 |