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:
def validMountainArray(self, arr: List[int]) -> bool:
#i를 기준으로 작거나 같아야 한다.
#i를 찾아야 한다
#i가 길이보다 작아야 함
#i가 큰곳
if len(arr) < 3: return False
result = False
i = 0
while i < len(arr) - 1 and arr[i] < arr[i+1]:
i += 1
if i ==len(arr) - 1:
break
while 0 < i < len(arr) - 1 and arr[i] > arr[i+1]:
i += 1
if i == len(arr) - 1:
result = True
break
return result
결과를 보면 아시겠지만 좋은 코드는 아닙니다.
인터넷에서 찾던 중 나온 코드입니다. 참조하면 좋을 듯 합니다.(비슷하면서 다릅니다.)
https://favtutor.com/blogs/valid-mountain-array
Valid Mountain Array Problem with Solution (C++, Java & Python)
Understand the problem of the Valid Mountain Array with an example. Also, learn how to solve this problem with C++, Java and Python code.
favtutor.com
'알고리즘 > 배열(array)' 카테고리의 다른 글
Move Zeroes python (0) | 2023.07.05 |
---|---|
Replace Elements with Greatest Element on Right Side python (0) | 2023.07.03 |
Check If N and Its Double Exist python (0) | 2023.07.01 |
Remove Duplicates from Sorted Array python (0) | 2023.06.29 |
Merge Sorted Array python (0) | 2023.06.26 |