-
[leetcode] 941. Valid Mountain Array알고리즘 2021. 11. 12. 18:43
Description
정수 배열이 주어졌을때 , 산(mountain) 의 형태로 된 정렬이라면 true 를 반환하는 문제
(오름차순 -> 내림차순)
Input: arr = [2, 1]
Output: false
Input: arr = [3, 5, 5]
Output: false
Input: arr = [0, 3, 2, 1]
Output: true
Success
배열의 원소는 최소 2개 이상이여야 하고 최초 시작은 무조건 오름차순으로 가야하기 때문에 [0] 번째 원소가 [1] 번째 원소보다 크면 안된다.
첫번째 while 문을 통해 이전 인덱스가 현재 인덱스 보다 클 때까지 계속 반복한다. 만약, 이전 인덱스가 현재 인덱스보다 크다면 종료 후 다음 while 문으로 이동하여 현재 인덱스부터 계속 값이 작은지를 확인한 후 해당 조건이 맞다면 true 를 반환시킨다.
class Solution { public static boolean validMountainArray(int[] arr) { if (arr == null || arr.length < 3 || arr[0] > arr[1]) return false; int i = 1; while (i < arr.length) { if (arr[i-1] > arr[i]) { break; } if (arr[i-1] == arr[i] || i == arr.length-1) { return false; } i++; } while (i < arr.length) { if (arr[i-1] <= arr[i]) { return false; } if (i == arr.length-1) { return true; } i++; } return false; } }
출처
'알고리즘' 카테고리의 다른 글
[leetcode] 26. Remove Duplicates from Sorted Array (0) 2021.11.16 [leetcode] Replace Elements with Greatest Element on Right Side (0) 2021.11.13 [leetcode] Check If N and Its Double Exist (0) 2021.11.12 [leetcode] 27. Remove Element (0) 2021.11.09 [leetcode] 88. Merge Sorted Array (0) 2021.11.08