반응형
https://leetcode.com/problems/monotonic-array/description/
Monotonic Array - LeetCode
Can you solve this real interview question? Monotonic Array - An array is monotonic if it is either monotone increasing or monotone decreasing. An array nums is monotone increasing if for all i <= j, nums[i] <= nums[j]. An array nums is monotone decreasing
leetcode.com
구현 문제였습니다.
📕 풀이방법
📔 입력 및 초기화
증가하는지 여부를 알기 위한 변수 isIncrease를 선언 후 -1로 초기화해줍니다. 증가한다면 1 아니면 0값을 저장합니다.
📔 풀이과정
nums원소에 대해 for loop를 수행합니다. 증가한다면 기존에 감소했었는지 확인 후 isIncrease를 1로 저장합니다. 반대로 감소한다면 기존에 증가했었는지 확인 후 isIncrease를 0으로 저장합니다.
📔 정답 출력 | 반환
기존 형태와 다르게 수가 증가하거나 감소했다면 false를, 아니라면 loop탈출 후 true를 반환합니다.
📕 Code
📔 C++
class Solution {
public:
bool isMonotonic(vector<int>& nums) {
int isIncrease = -1;
for(int i = 0; i < nums.size() - 1; i++) {
if(nums[i] == nums[i+1]) continue;
if(nums[i] < nums[i+1]) {
if(isIncrease == 0) return false;
isIncrease = 1;
} else {
if(isIncrease == 1) return false;
isIncrease = 0;
}
}
return true;
}
};
📔 Rust
impl Solution {
pub fn is_monotonic(nums: Vec<i32>) -> bool {
let mut isIncrease = -1;
for i in 0..nums.len()-1 {
if nums[i] == nums[i+1] {
continue;
}
if nums[i] < nums[i+1] {
if isIncrease == 0 {
return false;
}
isIncrease = 1;
} else {
if isIncrease == 1 {
return false;
}
isIncrease = 0;
}
}
return true
}
}
*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.
'Algorithm > Implementation' 카테고리의 다른 글
(C++, Rust) - LeetCode (easy) 922. Sort Array By Parity II (0) | 2023.09.01 |
---|---|
(C++, Rust) - LeetCode (easy) 908. Smallest Range I (0) | 2023.08.28 |
(C++, Rust) - LeetCode (easy) 892. Surface Area of 3D Shapes (0) | 2023.08.18 |
(C++) - LeetCode (easy) 696. Count Binary Substrings (0) | 2023.08.10 |
(C++) - LeetCode (easy) 883. Projection Area of 3D Shapes (0) | 2023.08.09 |