본문 바로가기

Algorithm/Implementation

(C++, Rust) - LeetCode (easy) 896. Monotonic Array

반응형

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
    }
}

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.