[코테 풀이] Monotonic Array

시내·2024년 6월 7일

Q_896) Monotonic Array

출처 : https://leetcode.com/problems/monotonic-array/?envType=study-plan-v2&envId=programming-skills

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 if for all i <= j, nums[i] >= nums[j].

Given an integer array nums, return true if the given array is monotonic, or false otherwise.

class Solution {
    public boolean isMonotonic(int[] nums) {
        if (nums.length == 1) return true;
        else {
            boolean increasing = nums[1] - nums[0] > 0 ? true : false;

            for (int q = 0; q < nums.length - 1; q++) {
                if (nums[q] != nums[q + 1]) {
                    if (nums[q + 1] > nums[q]) {
                        increasing = true;
                        break;
                    } else {
                        increasing = false;
                        break;
                    }
                }
            }
            if (increasing) {
                for (int i = 1; i < nums.length - 1; i++) {
                    if (nums[i] > nums[i + 1]) {
                        return false;
                    }
                }
            } else if (!increasing) { //decreasing
                for (int i = 1; i < nums.length - 1; i++) {
                    if (nums[i] < nums[i + 1]) {
                        return false;
                    }
                }
            }
            return true;
        }
    }
}
profile
contact 📨 ksw08215@gmail.com

0개의 댓글